git_panel.rs

   1use crate::askpass_modal::AskPassModal;
   2use crate::commit_modal::CommitModal;
   3use crate::git_panel_settings::StatusStyle;
   4use crate::project_diff::Diff;
   5use crate::remote_output_toast::{RemoteAction, RemoteOutputToast};
   6use crate::repository_selector::filtered_repository_entries;
   7use crate::{branch_picker, render_remote_button};
   8use crate::{
   9    git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,
  10};
  11use crate::{picker_prompt, project_diff, ProjectDiff};
  12use anyhow::Result;
  13use askpass::AskPassDelegate;
  14use db::kvp::KEY_VALUE_STORE;
  15use editor::commit_tooltip::CommitTooltip;
  16
  17use editor::{
  18    scroll::ScrollbarAutoHide, Editor, EditorElement, EditorMode, EditorSettings, MultiBuffer,
  19    ShowScrollbar,
  20};
  21use futures::StreamExt as _;
  22use git::repository::{
  23    Branch, CommitDetails, CommitSummary, DiffType, PushOptions, Remote, RemoteCommandOutput,
  24    ResetMode, Upstream, UpstreamTracking, UpstreamTrackingStatus,
  25};
  26use git::status::StageStatus;
  27use git::{repository::RepoPath, status::FileStatus, Commit, ToggleStaged};
  28use git::{ExpandCommitEditor, RestoreTrackedFiles, StageAll, TrashUntrackedFiles, UnstageAll};
  29use gpui::{
  30    actions, anchored, deferred, percentage, uniform_list, Action, Animation, AnimationExt as _,
  31    ClickEvent, Corner, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, KeyContext,
  32    ListHorizontalSizingBehavior, ListSizingBehavior, Modifiers, ModifiersChangedEvent,
  33    MouseButton, MouseDownEvent, Point, PromptLevel, ScrollStrategy, Stateful, Subscription, Task,
  34    Transformation, UniformListScrollHandle, WeakEntity,
  35};
  36use itertools::Itertools;
  37use language::{Buffer, File};
  38use language_model::{
  39    LanguageModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage, Role,
  40};
  41use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};
  42use multi_buffer::ExcerptInfo;
  43use panel::{
  44    panel_editor_container, panel_editor_style, panel_filled_button, panel_icon_button, PanelHeader,
  45};
  46use project::{
  47    git::{GitEvent, Repository},
  48    Fs, Project, ProjectPath,
  49};
  50use serde::{Deserialize, Serialize};
  51use settings::Settings as _;
  52use std::cell::RefCell;
  53use std::future::Future;
  54use std::path::{Path, PathBuf};
  55use std::rc::Rc;
  56use std::{collections::HashSet, sync::Arc, time::Duration, usize};
  57use strum::{IntoEnumIterator, VariantNames};
  58use time::OffsetDateTime;
  59use ui::{
  60    prelude::*, Checkbox, ContextMenu, ElevationIndex, PopoverMenu, Scrollbar, ScrollbarState,
  61    Tooltip,
  62};
  63use util::{maybe, post_inc, ResultExt, TryFutureExt};
  64use workspace::{AppState, OpenOptions, OpenVisible};
  65
  66use workspace::{
  67    dock::{DockPosition, Panel, PanelEvent},
  68    notifications::{DetachAndPromptErr, NotificationId},
  69    Toast, Workspace,
  70};
  71
  72actions!(
  73    git_panel,
  74    [
  75        Close,
  76        ToggleFocus,
  77        OpenMenu,
  78        FocusEditor,
  79        FocusChanges,
  80        ToggleFillCoAuthors,
  81        GenerateCommitMessage
  82    ]
  83);
  84
  85fn prompt<T>(
  86    msg: &str,
  87    detail: Option<&str>,
  88    window: &mut Window,
  89    cx: &mut App,
  90) -> Task<anyhow::Result<T>>
  91where
  92    T: IntoEnumIterator + VariantNames + 'static,
  93{
  94    let rx = window.prompt(PromptLevel::Info, msg, detail, &T::VARIANTS, cx);
  95    cx.spawn(|_| async move { Ok(T::iter().nth(rx.await?).unwrap()) })
  96}
  97
  98#[derive(strum::EnumIter, strum::VariantNames)]
  99#[strum(serialize_all = "title_case")]
 100enum TrashCancel {
 101    Trash,
 102    Cancel,
 103}
 104
 105fn git_panel_context_menu(
 106    focus_handle: Option<FocusHandle>,
 107    window: &mut Window,
 108    cx: &mut App,
 109) -> Entity<ContextMenu> {
 110    ContextMenu::build(window, cx, |context_menu, _, _| {
 111        context_menu
 112            .when_some(focus_handle, |el, focus_handle| el.context(focus_handle))
 113            .action("Stage All", StageAll.boxed_clone())
 114            .action("Unstage All", UnstageAll.boxed_clone())
 115            .separator()
 116            .action("Open Diff", project_diff::Diff.boxed_clone())
 117            .separator()
 118            .action("Discard Tracked Changes", RestoreTrackedFiles.boxed_clone())
 119            .action("Trash Untracked Files", TrashUntrackedFiles.boxed_clone())
 120    })
 121}
 122
 123const GIT_PANEL_KEY: &str = "GitPanel";
 124
 125const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
 126
 127pub fn init(cx: &mut App) {
 128    cx.observe_new(
 129        |workspace: &mut Workspace, _window, _: &mut Context<Workspace>| {
 130            workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
 131                workspace.toggle_panel_focus::<GitPanel>(window, cx);
 132            });
 133            workspace.register_action(|workspace, _: &ExpandCommitEditor, window, cx| {
 134                CommitModal::toggle(workspace, window, cx)
 135            });
 136        },
 137    )
 138    .detach();
 139}
 140
 141#[derive(Debug, Clone)]
 142pub enum Event {
 143    Focus,
 144}
 145
 146#[derive(Serialize, Deserialize)]
 147struct SerializedGitPanel {
 148    width: Option<Pixels>,
 149}
 150
 151#[derive(Debug, PartialEq, Eq, Clone, Copy)]
 152enum Section {
 153    Conflict,
 154    Tracked,
 155    New,
 156}
 157
 158#[derive(Debug, PartialEq, Eq, Clone)]
 159struct GitHeaderEntry {
 160    header: Section,
 161}
 162
 163impl GitHeaderEntry {
 164    pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {
 165        let this = &self.header;
 166        let status = status_entry.status;
 167        match this {
 168            Section::Conflict => repo.has_conflict(&status_entry.repo_path),
 169            Section::Tracked => !status.is_created(),
 170            Section::New => status.is_created(),
 171        }
 172    }
 173    pub fn title(&self) -> &'static str {
 174        match self.header {
 175            Section::Conflict => "Conflicts",
 176            Section::Tracked => "Tracked",
 177            Section::New => "Untracked",
 178        }
 179    }
 180}
 181
 182#[derive(Debug, PartialEq, Eq, Clone)]
 183enum GitListEntry {
 184    GitStatusEntry(GitStatusEntry),
 185    Header(GitHeaderEntry),
 186}
 187
 188impl GitListEntry {
 189    fn status_entry(&self) -> Option<&GitStatusEntry> {
 190        match self {
 191            GitListEntry::GitStatusEntry(entry) => Some(entry),
 192            _ => None,
 193        }
 194    }
 195}
 196
 197#[derive(Debug, PartialEq, Eq, Clone)]
 198pub struct GitStatusEntry {
 199    pub(crate) repo_path: RepoPath,
 200    pub(crate) worktree_path: Arc<Path>,
 201    pub(crate) abs_path: PathBuf,
 202    pub(crate) status: FileStatus,
 203    pub(crate) staging: StageStatus,
 204}
 205
 206#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 207enum TargetStatus {
 208    Staged,
 209    Unstaged,
 210    Reverted,
 211    Unchanged,
 212}
 213
 214struct PendingOperation {
 215    finished: bool,
 216    target_status: TargetStatus,
 217    entries: Vec<GitStatusEntry>,
 218    op_id: usize,
 219}
 220
 221type RemoteOperations = Rc<RefCell<HashSet<u32>>>;
 222
 223pub struct GitPanel {
 224    remote_operation_id: u32,
 225    pending_remote_operations: RemoteOperations,
 226    pub(crate) active_repository: Option<Entity<Repository>>,
 227    pub(crate) commit_editor: Entity<Editor>,
 228    conflicted_count: usize,
 229    conflicted_staged_count: usize,
 230    current_modifiers: Modifiers,
 231    add_coauthors: bool,
 232    generate_commit_message_task: Option<Task<Option<()>>>,
 233    entries: Vec<GitListEntry>,
 234    single_staged_entry: Option<GitStatusEntry>,
 235    single_tracked_entry: Option<GitStatusEntry>,
 236    focus_handle: FocusHandle,
 237    fs: Arc<dyn Fs>,
 238    hide_scrollbar_task: Option<Task<()>>,
 239    new_count: usize,
 240    entry_count: usize,
 241    new_staged_count: usize,
 242    pending: Vec<PendingOperation>,
 243    pending_commit: Option<Task<()>>,
 244    pending_serialization: Task<Option<()>>,
 245    pub(crate) project: Entity<Project>,
 246    scroll_handle: UniformListScrollHandle,
 247    scrollbar_state: ScrollbarState,
 248    selected_entry: Option<usize>,
 249    marked_entries: Vec<usize>,
 250    show_scrollbar: bool,
 251    tracked_count: usize,
 252    tracked_staged_count: usize,
 253    update_visible_entries_task: Task<()>,
 254    width: Option<Pixels>,
 255    workspace: WeakEntity<Workspace>,
 256    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
 257    modal_open: bool,
 258}
 259
 260struct RemoteOperationGuard {
 261    id: u32,
 262    pending_remote_operations: RemoteOperations,
 263}
 264
 265impl Drop for RemoteOperationGuard {
 266    fn drop(&mut self) {
 267        self.pending_remote_operations.borrow_mut().remove(&self.id);
 268    }
 269}
 270
 271pub(crate) fn commit_message_editor(
 272    commit_message_buffer: Entity<Buffer>,
 273    placeholder: Option<&str>,
 274    project: Entity<Project>,
 275    in_panel: bool,
 276    window: &mut Window,
 277    cx: &mut Context<'_, Editor>,
 278) -> Editor {
 279    let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, cx));
 280    let max_lines = if in_panel { 6 } else { 18 };
 281    let mut commit_editor = Editor::new(
 282        EditorMode::AutoHeight { max_lines },
 283        buffer,
 284        None,
 285        false,
 286        window,
 287        cx,
 288    );
 289    commit_editor.set_collaboration_hub(Box::new(project));
 290    commit_editor.set_use_autoclose(false);
 291    commit_editor.set_show_gutter(false, cx);
 292    commit_editor.set_show_wrap_guides(false, cx);
 293    commit_editor.set_show_indent_guides(false, cx);
 294    let placeholder = placeholder.unwrap_or("Enter commit message");
 295    commit_editor.set_placeholder_text(placeholder, cx);
 296    commit_editor
 297}
 298
 299impl GitPanel {
 300    pub fn new(
 301        workspace: Entity<Workspace>,
 302        project: Entity<Project>,
 303        app_state: Arc<AppState>,
 304        window: &mut Window,
 305        cx: &mut Context<Self>,
 306    ) -> Self {
 307        let fs = app_state.fs.clone();
 308        let git_store = project.read(cx).git_store().clone();
 309        let active_repository = project.read(cx).active_repository(cx);
 310        let workspace = workspace.downgrade();
 311
 312        let focus_handle = cx.focus_handle();
 313        cx.on_focus(&focus_handle, window, Self::focus_in).detach();
 314        cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
 315            this.hide_scrollbar(window, cx);
 316        })
 317        .detach();
 318
 319        // just to let us render a placeholder editor.
 320        // Once the active git repo is set, this buffer will be replaced.
 321        let temporary_buffer = cx.new(|cx| Buffer::local("", cx));
 322        let commit_editor = cx.new(|cx| {
 323            commit_message_editor(temporary_buffer, None, project.clone(), true, window, cx)
 324        });
 325
 326        commit_editor.update(cx, |editor, cx| {
 327            editor.clear(window, cx);
 328        });
 329
 330        let scroll_handle = UniformListScrollHandle::new();
 331
 332        cx.subscribe_in(
 333            &git_store,
 334            window,
 335            move |this, git_store, event, window, cx| match event {
 336                GitEvent::FileSystemUpdated => {
 337                    this.schedule_update(false, window, cx);
 338                }
 339                GitEvent::ActiveRepositoryChanged | GitEvent::GitStateUpdated => {
 340                    this.active_repository = git_store.read(cx).active_repository();
 341                    this.schedule_update(true, window, cx);
 342                }
 343                GitEvent::IndexWriteError(error) => {
 344                    this.workspace
 345                        .update(cx, |workspace, cx| {
 346                            workspace.show_error(error, cx);
 347                        })
 348                        .ok();
 349                }
 350            },
 351        )
 352        .detach();
 353
 354        let scrollbar_state =
 355            ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity());
 356
 357        let mut git_panel = Self {
 358            pending_remote_operations: Default::default(),
 359            remote_operation_id: 0,
 360            active_repository,
 361            commit_editor,
 362            conflicted_count: 0,
 363            conflicted_staged_count: 0,
 364            current_modifiers: window.modifiers(),
 365            add_coauthors: true,
 366            generate_commit_message_task: None,
 367            entries: Vec::new(),
 368            focus_handle: cx.focus_handle(),
 369            fs,
 370            hide_scrollbar_task: None,
 371            new_count: 0,
 372            new_staged_count: 0,
 373            pending: Vec::new(),
 374            pending_commit: None,
 375            pending_serialization: Task::ready(None),
 376            single_staged_entry: None,
 377            single_tracked_entry: None,
 378            project,
 379            scroll_handle,
 380            scrollbar_state,
 381            selected_entry: None,
 382            marked_entries: Vec::new(),
 383            show_scrollbar: false,
 384            tracked_count: 0,
 385            tracked_staged_count: 0,
 386            update_visible_entries_task: Task::ready(()),
 387            width: None,
 388            context_menu: None,
 389            workspace,
 390            modal_open: false,
 391            entry_count: 0,
 392        };
 393        git_panel.schedule_update(false, window, cx);
 394        git_panel.show_scrollbar = git_panel.should_show_scrollbar(cx);
 395        git_panel
 396    }
 397
 398    pub fn entry_by_path(&self, path: &RepoPath) -> Option<usize> {
 399        fn binary_search<F>(mut low: usize, mut high: usize, is_target: F) -> Option<usize>
 400        where
 401            F: Fn(usize) -> std::cmp::Ordering,
 402        {
 403            while low < high {
 404                let mid = low + (high - low) / 2;
 405                match is_target(mid) {
 406                    std::cmp::Ordering::Equal => return Some(mid),
 407                    std::cmp::Ordering::Less => low = mid + 1,
 408                    std::cmp::Ordering::Greater => high = mid,
 409                }
 410            }
 411            None
 412        }
 413        if self.conflicted_count > 0 {
 414            let conflicted_start = 1;
 415            if let Some(ix) = binary_search(
 416                conflicted_start,
 417                conflicted_start + self.conflicted_count,
 418                |ix| {
 419                    self.entries[ix]
 420                        .status_entry()
 421                        .unwrap()
 422                        .repo_path
 423                        .cmp(&path)
 424                },
 425            ) {
 426                return Some(ix);
 427            }
 428        }
 429        if self.tracked_count > 0 {
 430            let tracked_start = if self.conflicted_count > 0 {
 431                1 + self.conflicted_count
 432            } else {
 433                0
 434            } + 1;
 435            if let Some(ix) =
 436                binary_search(tracked_start, tracked_start + self.tracked_count, |ix| {
 437                    self.entries[ix]
 438                        .status_entry()
 439                        .unwrap()
 440                        .repo_path
 441                        .cmp(&path)
 442                })
 443            {
 444                return Some(ix);
 445            }
 446        }
 447        if self.new_count > 0 {
 448            let untracked_start = if self.conflicted_count > 0 {
 449                1 + self.conflicted_count
 450            } else {
 451                0
 452            } + if self.tracked_count > 0 {
 453                1 + self.tracked_count
 454            } else {
 455                0
 456            } + 1;
 457            if let Some(ix) =
 458                binary_search(untracked_start, untracked_start + self.new_count, |ix| {
 459                    self.entries[ix]
 460                        .status_entry()
 461                        .unwrap()
 462                        .repo_path
 463                        .cmp(&path)
 464                })
 465            {
 466                return Some(ix);
 467            }
 468        }
 469        None
 470    }
 471
 472    pub fn select_entry_by_path(
 473        &mut self,
 474        path: ProjectPath,
 475        _: &mut Window,
 476        cx: &mut Context<Self>,
 477    ) {
 478        let Some(git_repo) = self.active_repository.as_ref() else {
 479            return;
 480        };
 481        let Some(repo_path) = git_repo.read(cx).project_path_to_repo_path(&path) else {
 482            return;
 483        };
 484        let Some(ix) = self.entry_by_path(&repo_path) else {
 485            return;
 486        };
 487        self.selected_entry = Some(ix);
 488        cx.notify();
 489    }
 490
 491    fn start_remote_operation(&mut self) -> RemoteOperationGuard {
 492        let id = post_inc(&mut self.remote_operation_id);
 493        self.pending_remote_operations.borrow_mut().insert(id);
 494
 495        RemoteOperationGuard {
 496            id,
 497            pending_remote_operations: self.pending_remote_operations.clone(),
 498        }
 499    }
 500
 501    fn serialize(&mut self, cx: &mut Context<Self>) {
 502        let width = self.width;
 503        self.pending_serialization = cx.background_spawn(
 504            async move {
 505                KEY_VALUE_STORE
 506                    .write_kvp(
 507                        GIT_PANEL_KEY.into(),
 508                        serde_json::to_string(&SerializedGitPanel { width })?,
 509                    )
 510                    .await?;
 511                anyhow::Ok(())
 512            }
 513            .log_err(),
 514        );
 515    }
 516
 517    pub(crate) fn set_modal_open(&mut self, open: bool, cx: &mut Context<Self>) {
 518        self.modal_open = open;
 519        cx.notify();
 520    }
 521
 522    fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {
 523        let mut dispatch_context = KeyContext::new_with_defaults();
 524        dispatch_context.add("GitPanel");
 525
 526        if self.is_focused(window, cx) {
 527            dispatch_context.add("menu");
 528            dispatch_context.add("ChangesList");
 529        }
 530
 531        if self.commit_editor.read(cx).is_focused(window) {
 532            dispatch_context.add("CommitEditor");
 533        }
 534
 535        dispatch_context
 536    }
 537
 538    fn is_focused(&self, window: &Window, cx: &Context<Self>) -> bool {
 539        window
 540            .focused(cx)
 541            .map_or(false, |focused| self.focus_handle == focused)
 542    }
 543
 544    fn close_panel(&mut self, _: &Close, _window: &mut Window, cx: &mut Context<Self>) {
 545        cx.emit(PanelEvent::Close);
 546    }
 547
 548    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 549        if !self.focus_handle.contains_focused(window, cx) {
 550            cx.emit(Event::Focus);
 551        }
 552    }
 553
 554    fn show_scrollbar(&self, cx: &mut Context<Self>) -> ShowScrollbar {
 555        GitPanelSettings::get_global(cx)
 556            .scrollbar
 557            .show
 558            .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
 559    }
 560
 561    fn should_show_scrollbar(&self, cx: &mut Context<Self>) -> bool {
 562        let show = self.show_scrollbar(cx);
 563        match show {
 564            ShowScrollbar::Auto => true,
 565            ShowScrollbar::System => true,
 566            ShowScrollbar::Always => true,
 567            ShowScrollbar::Never => false,
 568        }
 569    }
 570
 571    fn should_autohide_scrollbar(&self, cx: &mut Context<Self>) -> bool {
 572        let show = self.show_scrollbar(cx);
 573        match show {
 574            ShowScrollbar::Auto => true,
 575            ShowScrollbar::System => cx
 576                .try_global::<ScrollbarAutoHide>()
 577                .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
 578            ShowScrollbar::Always => false,
 579            ShowScrollbar::Never => true,
 580        }
 581    }
 582
 583    fn hide_scrollbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 584        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
 585        if !self.should_autohide_scrollbar(cx) {
 586            return;
 587        }
 588        self.hide_scrollbar_task = Some(cx.spawn_in(window, |panel, mut cx| async move {
 589            cx.background_executor()
 590                .timer(SCROLLBAR_SHOW_INTERVAL)
 591                .await;
 592            panel
 593                .update(&mut cx, |panel, cx| {
 594                    panel.show_scrollbar = false;
 595                    cx.notify();
 596                })
 597                .log_err();
 598        }))
 599    }
 600
 601    fn handle_modifiers_changed(
 602        &mut self,
 603        event: &ModifiersChangedEvent,
 604        _: &mut Window,
 605        cx: &mut Context<Self>,
 606    ) {
 607        self.current_modifiers = event.modifiers;
 608        cx.notify();
 609    }
 610
 611    fn scroll_to_selected_entry(&mut self, cx: &mut Context<Self>) {
 612        if let Some(selected_entry) = self.selected_entry {
 613            self.scroll_handle
 614                .scroll_to_item(selected_entry, ScrollStrategy::Center);
 615        }
 616
 617        cx.notify();
 618    }
 619
 620    fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
 621        if !self.entries.is_empty() {
 622            self.selected_entry = Some(1);
 623            self.scroll_to_selected_entry(cx);
 624        }
 625    }
 626
 627    fn select_previous(
 628        &mut self,
 629        _: &SelectPrevious,
 630        _window: &mut Window,
 631        cx: &mut Context<Self>,
 632    ) {
 633        let item_count = self.entries.len();
 634        if item_count == 0 {
 635            return;
 636        }
 637
 638        if let Some(selected_entry) = self.selected_entry {
 639            let new_selected_entry = if selected_entry > 0 {
 640                selected_entry - 1
 641            } else {
 642                selected_entry
 643            };
 644
 645            if matches!(
 646                self.entries.get(new_selected_entry),
 647                Some(GitListEntry::Header(..))
 648            ) {
 649                if new_selected_entry > 0 {
 650                    self.selected_entry = Some(new_selected_entry - 1)
 651                }
 652            } else {
 653                self.selected_entry = Some(new_selected_entry);
 654            }
 655
 656            self.scroll_to_selected_entry(cx);
 657        }
 658
 659        cx.notify();
 660    }
 661
 662    fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
 663        let item_count = self.entries.len();
 664        if item_count == 0 {
 665            return;
 666        }
 667
 668        if let Some(selected_entry) = self.selected_entry {
 669            let new_selected_entry = if selected_entry < item_count - 1 {
 670                selected_entry + 1
 671            } else {
 672                selected_entry
 673            };
 674            if matches!(
 675                self.entries.get(new_selected_entry),
 676                Some(GitListEntry::Header(..))
 677            ) {
 678                self.selected_entry = Some(new_selected_entry + 1);
 679            } else {
 680                self.selected_entry = Some(new_selected_entry);
 681            }
 682
 683            self.scroll_to_selected_entry(cx);
 684        }
 685
 686        cx.notify();
 687    }
 688
 689    fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
 690        if self.entries.last().is_some() {
 691            self.selected_entry = Some(self.entries.len() - 1);
 692            self.scroll_to_selected_entry(cx);
 693        }
 694    }
 695
 696    pub(crate) fn editor_focus_handle(&self, cx: &mut Context<Self>) -> FocusHandle {
 697        self.commit_editor.focus_handle(cx).clone()
 698    }
 699
 700    fn focus_editor(&mut self, _: &FocusEditor, window: &mut Window, cx: &mut Context<Self>) {
 701        self.commit_editor.update(cx, |editor, cx| {
 702            window.focus(&editor.focus_handle(cx));
 703        });
 704        cx.notify();
 705    }
 706
 707    fn select_first_entry_if_none(&mut self, cx: &mut Context<Self>) {
 708        let have_entries = self
 709            .active_repository
 710            .as_ref()
 711            .map_or(false, |active_repository| {
 712                active_repository.read(cx).entry_count() > 0
 713            });
 714        if have_entries && self.selected_entry.is_none() {
 715            self.selected_entry = Some(1);
 716            self.scroll_to_selected_entry(cx);
 717            cx.notify();
 718        }
 719    }
 720
 721    fn focus_changes_list(
 722        &mut self,
 723        _: &FocusChanges,
 724        window: &mut Window,
 725        cx: &mut Context<Self>,
 726    ) {
 727        self.select_first_entry_if_none(cx);
 728
 729        cx.focus_self(window);
 730        cx.notify();
 731    }
 732
 733    fn get_selected_entry(&self) -> Option<&GitListEntry> {
 734        self.selected_entry.and_then(|i| self.entries.get(i))
 735    }
 736
 737    fn open_diff(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
 738        maybe!({
 739            let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
 740            let workspace = self.workspace.upgrade()?;
 741            let git_repo = self.active_repository.as_ref()?;
 742
 743            if let Some(project_diff) = workspace.read(cx).active_item_as::<ProjectDiff>(cx) {
 744                if let Some(project_path) = project_diff.read(cx).active_path(cx) {
 745                    if Some(&entry.repo_path)
 746                        == git_repo
 747                            .read(cx)
 748                            .project_path_to_repo_path(&project_path)
 749                            .as_ref()
 750                    {
 751                        project_diff.focus_handle(cx).focus(window);
 752                        project_diff.update(cx, |project_diff, cx| project_diff.autoscroll(cx));
 753                        return None;
 754                    }
 755                }
 756            };
 757
 758            if entry.worktree_path.starts_with("..") {
 759                self.workspace
 760                    .update(cx, |workspace, cx| {
 761                        workspace
 762                            .open_abs_path(
 763                                entry.abs_path.clone(),
 764                                OpenOptions {
 765                                    visible: Some(OpenVisible::All),
 766                                    focus: Some(false),
 767                                    ..Default::default()
 768                                },
 769                                window,
 770                                cx,
 771                            )
 772                            .detach_and_log_err(cx);
 773                    })
 774                    .ok();
 775            } else {
 776                self.workspace
 777                    .update(cx, |workspace, cx| {
 778                        ProjectDiff::deploy_at(workspace, Some(entry.clone()), window, cx);
 779                    })
 780                    .ok();
 781                self.focus_handle.focus(window);
 782            }
 783
 784            Some(())
 785        });
 786    }
 787
 788    fn open_file(
 789        &mut self,
 790        _: &menu::SecondaryConfirm,
 791        window: &mut Window,
 792        cx: &mut Context<Self>,
 793    ) {
 794        maybe!({
 795            let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
 796            let active_repo = self.active_repository.as_ref()?;
 797            let path = active_repo
 798                .read(cx)
 799                .repo_path_to_project_path(&entry.repo_path)?;
 800            if entry.status.is_deleted() {
 801                return None;
 802            }
 803
 804            self.workspace
 805                .update(cx, |workspace, cx| {
 806                    workspace
 807                        .open_path_preview(path, None, false, false, true, window, cx)
 808                        .detach_and_prompt_err("Failed to open file", window, cx, |e, _, _| {
 809                            Some(format!("{e}"))
 810                        });
 811                })
 812                .ok()
 813        });
 814    }
 815
 816    fn revert_selected(
 817        &mut self,
 818        _: &git::RestoreFile,
 819        window: &mut Window,
 820        cx: &mut Context<Self>,
 821    ) {
 822        maybe!({
 823            let list_entry = self.entries.get(self.selected_entry?)?.clone();
 824            let entry = list_entry.status_entry()?;
 825            self.revert_entry(&entry, window, cx);
 826            Some(())
 827        });
 828    }
 829
 830    fn revert_entry(
 831        &mut self,
 832        entry: &GitStatusEntry,
 833        window: &mut Window,
 834        cx: &mut Context<Self>,
 835    ) {
 836        maybe!({
 837            let active_repo = self.active_repository.clone()?;
 838            let path = active_repo
 839                .read(cx)
 840                .repo_path_to_project_path(&entry.repo_path)?;
 841            let workspace = self.workspace.clone();
 842
 843            if entry.status.staging().has_staged() {
 844                self.change_file_stage(false, vec![entry.clone()], cx);
 845            }
 846            let filename = path.path.file_name()?.to_string_lossy();
 847
 848            if !entry.status.is_created() {
 849                self.perform_checkout(vec![entry.clone()], cx);
 850            } else {
 851                let prompt = prompt(&format!("Trash {}?", filename), None, window, cx);
 852                cx.spawn_in(window, |_, mut cx| async move {
 853                    match prompt.await? {
 854                        TrashCancel::Trash => {}
 855                        TrashCancel::Cancel => return Ok(()),
 856                    }
 857                    let task = workspace.update(&mut cx, |workspace, cx| {
 858                        workspace
 859                            .project()
 860                            .update(cx, |project, cx| project.delete_file(path, true, cx))
 861                    })?;
 862                    if let Some(task) = task {
 863                        task.await?;
 864                    }
 865                    Ok(())
 866                })
 867                .detach_and_prompt_err(
 868                    "Failed to trash file",
 869                    window,
 870                    cx,
 871                    |e, _, _| Some(format!("{e}")),
 872                );
 873            }
 874            Some(())
 875        });
 876    }
 877
 878    fn perform_checkout(&mut self, entries: Vec<GitStatusEntry>, cx: &mut Context<Self>) {
 879        let workspace = self.workspace.clone();
 880        let Some(active_repository) = self.active_repository.clone() else {
 881            return;
 882        };
 883
 884        let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
 885        self.pending.push(PendingOperation {
 886            op_id,
 887            target_status: TargetStatus::Reverted,
 888            entries: entries.clone(),
 889            finished: false,
 890        });
 891        self.update_visible_entries(cx);
 892        let task = cx.spawn(|_, mut cx| async move {
 893            let tasks: Vec<_> = workspace.update(&mut cx, |workspace, cx| {
 894                workspace.project().update(cx, |project, cx| {
 895                    entries
 896                        .iter()
 897                        .filter_map(|entry| {
 898                            let path = active_repository
 899                                .read(cx)
 900                                .repo_path_to_project_path(&entry.repo_path)?;
 901                            Some(project.open_buffer(path, cx))
 902                        })
 903                        .collect()
 904                })
 905            })?;
 906
 907            let buffers = futures::future::join_all(tasks).await;
 908
 909            active_repository
 910                .update(&mut cx, |repo, cx| {
 911                    repo.checkout_files(
 912                        "HEAD",
 913                        entries
 914                            .iter()
 915                            .map(|entries| entries.repo_path.clone())
 916                            .collect(),
 917                        cx,
 918                    )
 919                })?
 920                .await??;
 921
 922            let tasks: Vec<_> = cx.update(|cx| {
 923                buffers
 924                    .iter()
 925                    .filter_map(|buffer| {
 926                        buffer.as_ref().ok()?.update(cx, |buffer, cx| {
 927                            buffer.is_dirty().then(|| buffer.reload(cx))
 928                        })
 929                    })
 930                    .collect()
 931            })?;
 932
 933            futures::future::join_all(tasks).await;
 934
 935            Ok(())
 936        });
 937
 938        cx.spawn(|this, mut cx| async move {
 939            let result = task.await;
 940
 941            this.update(&mut cx, |this, cx| {
 942                for pending in this.pending.iter_mut() {
 943                    if pending.op_id == op_id {
 944                        pending.finished = true;
 945                        if result.is_err() {
 946                            pending.target_status = TargetStatus::Unchanged;
 947                            this.update_visible_entries(cx);
 948                        }
 949                        break;
 950                    }
 951                }
 952                result
 953                    .map_err(|e| {
 954                        this.show_err_toast(e, cx);
 955                    })
 956                    .ok();
 957            })
 958            .ok();
 959        })
 960        .detach();
 961    }
 962
 963    fn restore_tracked_files(
 964        &mut self,
 965        _: &RestoreTrackedFiles,
 966        window: &mut Window,
 967        cx: &mut Context<Self>,
 968    ) {
 969        let entries = self
 970            .entries
 971            .iter()
 972            .filter_map(|entry| entry.status_entry().cloned())
 973            .filter(|status_entry| !status_entry.status.is_created())
 974            .collect::<Vec<_>>();
 975
 976        match entries.len() {
 977            0 => return,
 978            1 => return self.revert_entry(&entries[0], window, cx),
 979            _ => {}
 980        }
 981        let mut details = entries
 982            .iter()
 983            .filter_map(|entry| entry.repo_path.0.file_name())
 984            .map(|filename| filename.to_string_lossy())
 985            .take(5)
 986            .join("\n");
 987        if entries.len() > 5 {
 988            details.push_str(&format!("\nand {} more…", entries.len() - 5))
 989        }
 990
 991        #[derive(strum::EnumIter, strum::VariantNames)]
 992        #[strum(serialize_all = "title_case")]
 993        enum RestoreCancel {
 994            RestoreTrackedFiles,
 995            Cancel,
 996        }
 997        let prompt = prompt(
 998            "Discard changes to these files?",
 999            Some(&details),
1000            window,
1001            cx,
1002        );
1003        cx.spawn(|this, mut cx| async move {
1004            match prompt.await {
1005                Ok(RestoreCancel::RestoreTrackedFiles) => {
1006                    this.update(&mut cx, |this, cx| {
1007                        this.perform_checkout(entries, cx);
1008                    })
1009                    .ok();
1010                }
1011                _ => {
1012                    return;
1013                }
1014            }
1015        })
1016        .detach();
1017    }
1018
1019    fn clean_all(&mut self, _: &TrashUntrackedFiles, window: &mut Window, cx: &mut Context<Self>) {
1020        let workspace = self.workspace.clone();
1021        let Some(active_repo) = self.active_repository.clone() else {
1022            return;
1023        };
1024        let to_delete = self
1025            .entries
1026            .iter()
1027            .filter_map(|entry| entry.status_entry())
1028            .filter(|status_entry| status_entry.status.is_created())
1029            .cloned()
1030            .collect::<Vec<_>>();
1031
1032        match to_delete.len() {
1033            0 => return,
1034            1 => return self.revert_entry(&to_delete[0], window, cx),
1035            _ => {}
1036        };
1037
1038        let mut details = to_delete
1039            .iter()
1040            .map(|entry| {
1041                entry
1042                    .repo_path
1043                    .0
1044                    .file_name()
1045                    .map(|f| f.to_string_lossy())
1046                    .unwrap_or_default()
1047            })
1048            .take(5)
1049            .join("\n");
1050
1051        if to_delete.len() > 5 {
1052            details.push_str(&format!("\nand {} more…", to_delete.len() - 5))
1053        }
1054
1055        let prompt = prompt("Trash these files?", Some(&details), window, cx);
1056        cx.spawn_in(window, |this, mut cx| async move {
1057            match prompt.await? {
1058                TrashCancel::Trash => {}
1059                TrashCancel::Cancel => return Ok(()),
1060            }
1061            let tasks = workspace.update(&mut cx, |workspace, cx| {
1062                to_delete
1063                    .iter()
1064                    .filter_map(|entry| {
1065                        workspace.project().update(cx, |project, cx| {
1066                            let project_path = active_repo
1067                                .read(cx)
1068                                .repo_path_to_project_path(&entry.repo_path)?;
1069                            project.delete_file(project_path, true, cx)
1070                        })
1071                    })
1072                    .collect::<Vec<_>>()
1073            })?;
1074            let to_unstage = to_delete
1075                .into_iter()
1076                .filter(|entry| !entry.status.staging().is_fully_unstaged())
1077                .collect();
1078            this.update(&mut cx, |this, cx| {
1079                this.change_file_stage(false, to_unstage, cx)
1080            })?;
1081            for task in tasks {
1082                task.await?;
1083            }
1084            Ok(())
1085        })
1086        .detach_and_prompt_err("Failed to trash files", window, cx, |e, _, _| {
1087            Some(format!("{e}"))
1088        });
1089    }
1090
1091    pub fn stage_all(&mut self, _: &StageAll, _window: &mut Window, cx: &mut Context<Self>) {
1092        let entries = self
1093            .entries
1094            .iter()
1095            .filter_map(|entry| entry.status_entry())
1096            .filter(|status_entry| status_entry.staging.has_unstaged())
1097            .cloned()
1098            .collect::<Vec<_>>();
1099        self.change_file_stage(true, entries, cx);
1100    }
1101
1102    pub fn unstage_all(&mut self, _: &UnstageAll, _window: &mut Window, cx: &mut Context<Self>) {
1103        let entries = self
1104            .entries
1105            .iter()
1106            .filter_map(|entry| entry.status_entry())
1107            .filter(|status_entry| status_entry.staging.has_staged())
1108            .cloned()
1109            .collect::<Vec<_>>();
1110        self.change_file_stage(false, entries, cx);
1111    }
1112
1113    fn toggle_staged_for_entry(
1114        &mut self,
1115        entry: &GitListEntry,
1116        _window: &mut Window,
1117        cx: &mut Context<Self>,
1118    ) {
1119        let Some(active_repository) = self.active_repository.as_ref() else {
1120            return;
1121        };
1122        let (stage, repo_paths) = match entry {
1123            GitListEntry::GitStatusEntry(status_entry) => {
1124                if status_entry.status.staging().is_fully_staged() {
1125                    (false, vec![status_entry.clone()])
1126                } else {
1127                    (true, vec![status_entry.clone()])
1128                }
1129            }
1130            GitListEntry::Header(section) => {
1131                let goal_staged_state = !self.header_state(section.header).selected();
1132                let repository = active_repository.read(cx);
1133                let entries = self
1134                    .entries
1135                    .iter()
1136                    .filter_map(|entry| entry.status_entry())
1137                    .filter(|status_entry| {
1138                        section.contains(&status_entry, repository)
1139                            && status_entry.staging.as_bool() != Some(goal_staged_state)
1140                    })
1141                    .map(|status_entry| status_entry.clone())
1142                    .collect::<Vec<_>>();
1143
1144                (goal_staged_state, entries)
1145            }
1146        };
1147        self.change_file_stage(stage, repo_paths, cx);
1148    }
1149
1150    fn change_file_stage(
1151        &mut self,
1152        stage: bool,
1153        entries: Vec<GitStatusEntry>,
1154        cx: &mut Context<Self>,
1155    ) {
1156        let Some(active_repository) = self.active_repository.clone() else {
1157            return;
1158        };
1159        let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
1160        self.pending.push(PendingOperation {
1161            op_id,
1162            target_status: if stage {
1163                TargetStatus::Staged
1164            } else {
1165                TargetStatus::Unstaged
1166            },
1167            entries: entries.clone(),
1168            finished: false,
1169        });
1170        let repository = active_repository.read(cx);
1171        self.update_counts(repository);
1172        cx.notify();
1173
1174        cx.spawn({
1175            |this, mut cx| async move {
1176                let result = cx
1177                    .update(|cx| {
1178                        if stage {
1179                            active_repository.update(cx, |repo, cx| {
1180                                let repo_paths = entries
1181                                    .iter()
1182                                    .map(|entry| entry.repo_path.clone())
1183                                    .collect();
1184                                repo.stage_entries(repo_paths, cx)
1185                            })
1186                        } else {
1187                            active_repository.update(cx, |repo, cx| {
1188                                let repo_paths = entries
1189                                    .iter()
1190                                    .map(|entry| entry.repo_path.clone())
1191                                    .collect();
1192                                repo.unstage_entries(repo_paths, cx)
1193                            })
1194                        }
1195                    })?
1196                    .await;
1197
1198                this.update(&mut cx, |this, cx| {
1199                    for pending in this.pending.iter_mut() {
1200                        if pending.op_id == op_id {
1201                            pending.finished = true
1202                        }
1203                    }
1204                    result
1205                        .map_err(|e| {
1206                            this.show_err_toast(e, cx);
1207                        })
1208                        .ok();
1209                    cx.notify();
1210                })
1211            }
1212        })
1213        .detach();
1214    }
1215
1216    pub fn total_staged_count(&self) -> usize {
1217        self.tracked_staged_count + self.new_staged_count + self.conflicted_staged_count
1218    }
1219
1220    pub fn commit_message_buffer(&self, cx: &App) -> Entity<Buffer> {
1221        self.commit_editor
1222            .read(cx)
1223            .buffer()
1224            .read(cx)
1225            .as_singleton()
1226            .unwrap()
1227            .clone()
1228    }
1229
1230    fn toggle_staged_for_selected(
1231        &mut self,
1232        _: &git::ToggleStaged,
1233        window: &mut Window,
1234        cx: &mut Context<Self>,
1235    ) {
1236        if let Some(selected_entry) = self.get_selected_entry().cloned() {
1237            self.toggle_staged_for_entry(&selected_entry, window, cx);
1238        }
1239    }
1240
1241    fn stage_selected(&mut self, _: &git::StageFile, _window: &mut Window, cx: &mut Context<Self>) {
1242        let Some(selected_entry) = self.get_selected_entry() else {
1243            return;
1244        };
1245        let Some(status_entry) = selected_entry.status_entry() else {
1246            return;
1247        };
1248        if status_entry.staging != StageStatus::Staged {
1249            self.change_file_stage(true, vec![status_entry.clone()], cx);
1250        }
1251    }
1252
1253    fn unstage_selected(
1254        &mut self,
1255        _: &git::UnstageFile,
1256        _window: &mut Window,
1257        cx: &mut Context<Self>,
1258    ) {
1259        let Some(selected_entry) = self.get_selected_entry() else {
1260            return;
1261        };
1262        let Some(status_entry) = selected_entry.status_entry() else {
1263            return;
1264        };
1265        if status_entry.staging != StageStatus::Unstaged {
1266            self.change_file_stage(false, vec![status_entry.clone()], cx);
1267        }
1268    }
1269
1270    fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
1271        if self
1272            .commit_editor
1273            .focus_handle(cx)
1274            .contains_focused(window, cx)
1275        {
1276            telemetry::event!("Git Committed", source = "Git Panel");
1277            self.commit_changes(window, cx)
1278        } else {
1279            cx.propagate();
1280        }
1281    }
1282
1283    fn custom_or_suggested_commit_message(&self, cx: &mut Context<Self>) -> Option<String> {
1284        let message = self.commit_editor.read(cx).text(cx);
1285
1286        if !message.trim().is_empty() {
1287            return Some(message.to_string());
1288        }
1289
1290        self.suggest_commit_message()
1291            .filter(|message| !message.trim().is_empty())
1292    }
1293
1294    pub(crate) fn commit_changes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1295        let Some(active_repository) = self.active_repository.clone() else {
1296            return;
1297        };
1298        let error_spawn = |message, window: &mut Window, cx: &mut App| {
1299            let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
1300            cx.spawn(|_| async move {
1301                prompt.await.ok();
1302            })
1303            .detach();
1304        };
1305
1306        if self.has_unstaged_conflicts() {
1307            error_spawn(
1308                "There are still conflicts. You must stage these before committing",
1309                window,
1310                cx,
1311            );
1312            return;
1313        }
1314
1315        let commit_message = self.custom_or_suggested_commit_message(cx);
1316
1317        let Some(mut message) = commit_message else {
1318            self.commit_editor.read(cx).focus_handle(cx).focus(window);
1319            return;
1320        };
1321
1322        if self.add_coauthors {
1323            self.fill_co_authors(&mut message, cx);
1324        }
1325
1326        let task = if self.has_staged_changes() {
1327            // Repository serializes all git operations, so we can just send a commit immediately
1328            let commit_task =
1329                active_repository.update(cx, |repo, cx| repo.commit(message.into(), None, cx));
1330            cx.background_spawn(async move { commit_task.await? })
1331        } else {
1332            let changed_files = self
1333                .entries
1334                .iter()
1335                .filter_map(|entry| entry.status_entry())
1336                .filter(|status_entry| !status_entry.status.is_created())
1337                .map(|status_entry| status_entry.repo_path.clone())
1338                .collect::<Vec<_>>();
1339
1340            if changed_files.is_empty() {
1341                error_spawn("No changes to commit", window, cx);
1342                return;
1343            }
1344
1345            let stage_task =
1346                active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
1347            cx.spawn(|_, mut cx| async move {
1348                stage_task.await?;
1349                let commit_task = active_repository
1350                    .update(&mut cx, |repo, cx| repo.commit(message.into(), None, cx))?;
1351                commit_task.await?
1352            })
1353        };
1354        let task = cx.spawn_in(window, |this, mut cx| async move {
1355            let result = task.await;
1356            this.update_in(&mut cx, |this, window, cx| {
1357                this.pending_commit.take();
1358                match result {
1359                    Ok(()) => {
1360                        this.commit_editor
1361                            .update(cx, |editor, cx| editor.clear(window, cx));
1362                    }
1363                    Err(e) => this.show_err_toast(e, cx),
1364                }
1365            })
1366            .ok();
1367        });
1368
1369        self.pending_commit = Some(task);
1370    }
1371
1372    fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1373        let Some(repo) = self.active_repository.clone() else {
1374            return;
1375        };
1376        telemetry::event!("Git Uncommitted");
1377
1378        let confirmation = self.check_for_pushed_commits(window, cx);
1379        let prior_head = self.load_commit_details("HEAD", cx);
1380
1381        let task = cx.spawn_in(window, |this, mut cx| async move {
1382            let result = maybe!(async {
1383                if let Ok(true) = confirmation.await {
1384                    let prior_head = prior_head.await?;
1385
1386                    repo.update(&mut cx, |repo, cx| repo.reset("HEAD^", ResetMode::Soft, cx))?
1387                        .await??;
1388
1389                    Ok(Some(prior_head))
1390                } else {
1391                    Ok(None)
1392                }
1393            })
1394            .await;
1395
1396            this.update_in(&mut cx, |this, window, cx| {
1397                this.pending_commit.take();
1398                match result {
1399                    Ok(None) => {}
1400                    Ok(Some(prior_commit)) => {
1401                        this.commit_editor.update(cx, |editor, cx| {
1402                            editor.set_text(prior_commit.message, window, cx)
1403                        });
1404                    }
1405                    Err(e) => this.show_err_toast(e, cx),
1406                }
1407            })
1408            .ok();
1409        });
1410
1411        self.pending_commit = Some(task);
1412    }
1413
1414    fn check_for_pushed_commits(
1415        &mut self,
1416        window: &mut Window,
1417        cx: &mut Context<Self>,
1418    ) -> impl Future<Output = Result<bool, anyhow::Error>> {
1419        let repo = self.active_repository.clone();
1420        let mut cx = window.to_async(cx);
1421
1422        async move {
1423            let Some(repo) = repo else {
1424                return Err(anyhow::anyhow!("No active repository"));
1425            };
1426
1427            let pushed_to: Vec<SharedString> = repo
1428                .update(&mut cx, |repo, _| repo.check_for_pushed_commits())?
1429                .await??;
1430
1431            if pushed_to.is_empty() {
1432                Ok(true)
1433            } else {
1434                #[derive(strum::EnumIter, strum::VariantNames)]
1435                #[strum(serialize_all = "title_case")]
1436                enum CancelUncommit {
1437                    Uncommit,
1438                    Cancel,
1439                }
1440                let detail = format!(
1441                    "This commit was already pushed to {}.",
1442                    pushed_to.into_iter().join(", ")
1443                );
1444                let result = cx
1445                    .update(|window, cx| prompt("Are you sure?", Some(&detail), window, cx))?
1446                    .await?;
1447
1448                match result {
1449                    CancelUncommit::Cancel => Ok(false),
1450                    CancelUncommit::Uncommit => Ok(true),
1451                }
1452            }
1453        }
1454    }
1455
1456    /// Suggests a commit message based on the changed files and their statuses
1457    pub fn suggest_commit_message(&self) -> Option<String> {
1458        let git_status_entry = if let Some(staged_entry) = &self.single_staged_entry {
1459            Some(staged_entry)
1460        } else if let Some(single_tracked_entry) = &self.single_tracked_entry {
1461            Some(single_tracked_entry)
1462        } else {
1463            None
1464        }?;
1465
1466        let action_text = if git_status_entry.status.is_deleted() {
1467            Some("Delete")
1468        } else if git_status_entry.status.is_created() {
1469            Some("Create")
1470        } else if git_status_entry.status.is_modified() {
1471            Some("Update")
1472        } else {
1473            None
1474        }?;
1475
1476        let file_name = git_status_entry
1477            .repo_path
1478            .file_name()
1479            .unwrap_or_default()
1480            .to_string_lossy();
1481
1482        Some(format!("{} {}", action_text, file_name))
1483    }
1484
1485    fn generate_commit_message_action(
1486        &mut self,
1487        _: &git::GenerateCommitMessage,
1488        _window: &mut Window,
1489        cx: &mut Context<Self>,
1490    ) {
1491        self.generate_commit_message(cx);
1492    }
1493
1494    /// Generates a commit message using an LLM.
1495    pub fn generate_commit_message(&mut self, cx: &mut Context<Self>) {
1496        if !self.can_commit() {
1497            return;
1498        }
1499
1500        let model = match current_language_model(cx) {
1501            Some(value) => value,
1502            None => return,
1503        };
1504
1505        let Some(repo) = self.active_repository.as_ref() else {
1506            return;
1507        };
1508
1509        telemetry::event!("Git Commit Message Generated");
1510
1511        let diff = repo.update(cx, |repo, cx| {
1512            if self.has_staged_changes() {
1513                repo.diff(DiffType::HeadToIndex, cx)
1514            } else {
1515                repo.diff(DiffType::HeadToWorktree, cx)
1516            }
1517        });
1518
1519        self.generate_commit_message_task = Some(cx.spawn(|this, mut cx| {
1520            async move {
1521                let _defer = util::defer({
1522                    let mut cx = cx.clone();
1523                    let this = this.clone();
1524                    move || {
1525                        this.update(&mut cx, |this, _cx| {
1526                            this.generate_commit_message_task.take();
1527                        })
1528                        .ok();
1529                    }
1530                });
1531
1532                let mut diff_text = diff.await??;
1533
1534                const ONE_MB: usize = 1_000_000;
1535                if diff_text.len() > ONE_MB {
1536                    diff_text = diff_text.chars().take(ONE_MB).collect()
1537                }
1538
1539                let subject = this.update(&mut cx, |this, cx| {
1540                    this.commit_editor.read(cx).text(cx).lines().next().map(ToOwned::to_owned).unwrap_or_default()
1541                })?;
1542
1543                let text_empty = subject.trim().is_empty();
1544
1545                let content = if text_empty {
1546                    format!("{PROMPT}\nHere are the changes in this commit:\n{diff_text}")
1547                } else {
1548                    format!("{PROMPT}\nHere is the user's subject line:\n{subject}\nHere are the changes in this commit:\n{diff_text}\n")
1549                };
1550
1551                const PROMPT: &str = include_str!("commit_message_prompt.txt");
1552
1553                let request = LanguageModelRequest {
1554                    messages: vec![LanguageModelRequestMessage {
1555                        role: Role::User,
1556                        content: vec![content.into()],
1557                        cache: false,
1558                    }],
1559                    tools: Vec::new(),
1560                    stop: Vec::new(),
1561                    temperature: None,
1562                };
1563
1564                let stream = model.stream_completion_text(request, &cx);
1565                let mut messages = stream.await?;
1566
1567                if !text_empty {
1568                    this.update(&mut cx, |this, cx| {
1569                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1570                            let insert_position = buffer.anchor_before(buffer.len());
1571                            buffer.edit([(insert_position..insert_position, "\n")], None, cx)
1572                        });
1573                    })?;
1574                }
1575
1576                while let Some(message) = messages.stream.next().await {
1577                    let text = message?;
1578
1579                    this.update(&mut cx, |this, cx| {
1580                        this.commit_message_buffer(cx).update(cx, |buffer, cx| {
1581                            let insert_position = buffer.anchor_before(buffer.len());
1582                            buffer.edit([(insert_position..insert_position, text)], None, cx);
1583                        });
1584                    })?;
1585                }
1586
1587                anyhow::Ok(())
1588            }
1589            .log_err()
1590        }));
1591    }
1592
1593    fn update_editor_placeholder(&mut self, cx: &mut Context<Self>) {
1594        let suggested_commit_message = self.suggest_commit_message();
1595        let placeholder_text = suggested_commit_message
1596            .as_deref()
1597            .unwrap_or("Enter commit message");
1598
1599        self.commit_editor.update(cx, |editor, cx| {
1600            editor.set_placeholder_text(Arc::from(placeholder_text), cx)
1601        });
1602
1603        cx.notify();
1604    }
1605
1606    pub(crate) fn fetch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1607        if !self.can_push_and_pull(cx) {
1608            return;
1609        }
1610
1611        let Some(repo) = self.active_repository.clone() else {
1612            return;
1613        };
1614        telemetry::event!("Git Fetched");
1615        let guard = self.start_remote_operation();
1616        let askpass = self.askpass_delegate("git fetch", window, cx);
1617        cx.spawn(|this, mut cx| async move {
1618            let fetch = repo.update(&mut cx, |repo, cx| repo.fetch(askpass, cx))?;
1619
1620            let remote_message = fetch.await?;
1621            drop(guard);
1622            this.update(&mut cx, |this, cx| {
1623                match remote_message {
1624                    Ok(remote_message) => {
1625                        this.show_remote_output(RemoteAction::Fetch, remote_message, cx);
1626                    }
1627                    Err(e) => {
1628                        log::error!("Error while fetching {:?}", e);
1629                        this.show_err_toast(e, cx);
1630                    }
1631                }
1632
1633                anyhow::Ok(())
1634            })
1635            .ok();
1636            anyhow::Ok(())
1637        })
1638        .detach_and_log_err(cx);
1639    }
1640
1641    pub(crate) fn pull(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1642        if !self.can_push_and_pull(cx) {
1643            return;
1644        }
1645        let Some(repo) = self.active_repository.clone() else {
1646            return;
1647        };
1648        let Some(branch) = repo.read(cx).current_branch() else {
1649            return;
1650        };
1651        telemetry::event!("Git Pulled");
1652        let branch = branch.clone();
1653        let remote = self.get_current_remote(window, cx);
1654        cx.spawn_in(window, move |this, mut cx| async move {
1655            let remote = match remote.await {
1656                Ok(Some(remote)) => remote,
1657                Ok(None) => {
1658                    return Ok(());
1659                }
1660                Err(e) => {
1661                    log::error!("Failed to get current remote: {}", e);
1662                    this.update(&mut cx, |this, cx| this.show_err_toast(e, cx))
1663                        .ok();
1664                    return Ok(());
1665                }
1666            };
1667
1668            let askpass = this.update_in(&mut cx, |this, window, cx| {
1669                this.askpass_delegate(format!("git pull {}", remote.name), window, cx)
1670            })?;
1671
1672            let guard = this
1673                .update(&mut cx, |this, _| this.start_remote_operation())
1674                .ok();
1675
1676            let pull = repo.update(&mut cx, |repo, cx| {
1677                repo.pull(branch.name.clone(), remote.name.clone(), askpass, cx)
1678            })?;
1679
1680            let remote_message = pull.await?;
1681            drop(guard);
1682
1683            this.update(&mut cx, |this, cx| match remote_message {
1684                Ok(remote_message) => {
1685                    this.show_remote_output(RemoteAction::Pull, remote_message, cx)
1686                }
1687                Err(err) => {
1688                    log::error!("Error while pull {:?}", err);
1689                    this.show_err_toast(err, cx)
1690                }
1691            })
1692            .ok();
1693
1694            anyhow::Ok(())
1695        })
1696        .detach_and_log_err(cx);
1697    }
1698
1699    pub(crate) fn push(&mut self, force_push: bool, window: &mut Window, cx: &mut Context<Self>) {
1700        if !self.can_push_and_pull(cx) {
1701            return;
1702        }
1703        let Some(repo) = self.active_repository.clone() else {
1704            return;
1705        };
1706        let Some(branch) = repo.read(cx).current_branch() else {
1707            return;
1708        };
1709        telemetry::event!("Git Pushed");
1710        let branch = branch.clone();
1711        let options = if force_push {
1712            PushOptions::Force
1713        } else {
1714            PushOptions::SetUpstream
1715        };
1716        let remote = self.get_current_remote(window, cx);
1717
1718        cx.spawn_in(window, move |this, mut cx| async move {
1719            let remote = match remote.await {
1720                Ok(Some(remote)) => remote,
1721                Ok(None) => {
1722                    return Ok(());
1723                }
1724                Err(e) => {
1725                    log::error!("Failed to get current remote: {}", e);
1726                    this.update(&mut cx, |this, cx| this.show_err_toast(e, cx))
1727                        .ok();
1728                    return Ok(());
1729                }
1730            };
1731
1732            let askpass_delegate = this.update_in(&mut cx, |this, window, cx| {
1733                this.askpass_delegate(format!("git push {}", remote.name), window, cx)
1734            })?;
1735
1736            let guard = this
1737                .update(&mut cx, |this, _| this.start_remote_operation())
1738                .ok();
1739
1740            let push = repo.update(&mut cx, |repo, cx| {
1741                repo.push(
1742                    branch.name.clone(),
1743                    remote.name.clone(),
1744                    Some(options),
1745                    askpass_delegate,
1746                    cx,
1747                )
1748            })?;
1749
1750            let remote_output = push.await?;
1751            drop(guard);
1752
1753            this.update(&mut cx, |this, cx| match remote_output {
1754                Ok(remote_message) => {
1755                    this.show_remote_output(RemoteAction::Push(remote), remote_message, cx);
1756                }
1757                Err(e) => {
1758                    log::error!("Error while pushing {:?}", e);
1759                    this.show_err_toast(e, cx);
1760                }
1761            })?;
1762
1763            anyhow::Ok(())
1764        })
1765        .detach_and_log_err(cx);
1766    }
1767
1768    fn askpass_delegate(
1769        &self,
1770        operation: impl Into<SharedString>,
1771        window: &mut Window,
1772        cx: &mut Context<Self>,
1773    ) -> AskPassDelegate {
1774        let this = cx.weak_entity();
1775        let operation = operation.into();
1776        let window = window.window_handle();
1777        AskPassDelegate::new(&mut cx.to_async(), move |prompt, tx, cx| {
1778            window
1779                .update(cx, |_, window, cx| {
1780                    this.update(cx, |this, cx| {
1781                        this.workspace.update(cx, |workspace, cx| {
1782                            workspace.toggle_modal(window, cx, |window, cx| {
1783                                AskPassModal::new(operation.clone(), prompt.into(), tx, window, cx)
1784                            });
1785                        })
1786                    })
1787                })
1788                .ok();
1789        })
1790    }
1791
1792    fn can_push_and_pull(&self, cx: &App) -> bool {
1793        crate::can_push_and_pull(&self.project, cx)
1794    }
1795
1796    fn get_current_remote(
1797        &mut self,
1798        window: &mut Window,
1799        cx: &mut Context<Self>,
1800    ) -> impl Future<Output = anyhow::Result<Option<Remote>>> {
1801        let repo = self.active_repository.clone();
1802        let workspace = self.workspace.clone();
1803        let mut cx = window.to_async(cx);
1804
1805        async move {
1806            let Some(repo) = repo else {
1807                return Err(anyhow::anyhow!("No active repository"));
1808            };
1809
1810            let mut current_remotes: Vec<Remote> = repo
1811                .update(&mut cx, |repo, _| {
1812                    let Some(current_branch) = repo.current_branch() else {
1813                        return Err(anyhow::anyhow!("No active branch"));
1814                    };
1815
1816                    Ok(repo.get_remotes(Some(current_branch.name.to_string())))
1817                })??
1818                .await??;
1819
1820            if current_remotes.len() == 0 {
1821                return Err(anyhow::anyhow!("No active remote"));
1822            } else if current_remotes.len() == 1 {
1823                return Ok(Some(current_remotes.pop().unwrap()));
1824            } else {
1825                let current_remotes: Vec<_> = current_remotes
1826                    .into_iter()
1827                    .map(|remotes| remotes.name)
1828                    .collect();
1829                let selection = cx
1830                    .update(|window, cx| {
1831                        picker_prompt::prompt(
1832                            "Pick which remote to push to",
1833                            current_remotes.clone(),
1834                            workspace,
1835                            window,
1836                            cx,
1837                        )
1838                    })?
1839                    .await?;
1840
1841                Ok(selection.map(|selection| Remote {
1842                    name: current_remotes[selection].clone(),
1843                }))
1844            }
1845        }
1846    }
1847
1848    fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
1849        let mut new_co_authors = Vec::new();
1850        let project = self.project.read(cx);
1851
1852        let Some(room) = self
1853            .workspace
1854            .upgrade()
1855            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
1856        else {
1857            return Vec::default();
1858        };
1859
1860        let room = room.read(cx);
1861
1862        for (peer_id, collaborator) in project.collaborators() {
1863            if collaborator.is_host {
1864                continue;
1865            }
1866
1867            let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
1868                continue;
1869            };
1870            if participant.can_write() && participant.user.email.is_some() {
1871                let email = participant.user.email.clone().unwrap();
1872
1873                new_co_authors.push((
1874                    participant
1875                        .user
1876                        .name
1877                        .clone()
1878                        .unwrap_or_else(|| participant.user.github_login.clone()),
1879                    email,
1880                ))
1881            }
1882        }
1883        if !project.is_local() && !project.is_read_only(cx) {
1884            if let Some(user) = room.local_participant_user(cx) {
1885                if let Some(email) = user.email.clone() {
1886                    new_co_authors.push((
1887                        user.name
1888                            .clone()
1889                            .unwrap_or_else(|| user.github_login.clone()),
1890                        email.clone(),
1891                    ))
1892                }
1893            }
1894        }
1895        new_co_authors
1896    }
1897
1898    fn toggle_fill_co_authors(
1899        &mut self,
1900        _: &ToggleFillCoAuthors,
1901        _: &mut Window,
1902        cx: &mut Context<Self>,
1903    ) {
1904        self.add_coauthors = !self.add_coauthors;
1905        cx.notify();
1906    }
1907
1908    fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
1909        const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
1910
1911        let existing_text = message.to_ascii_lowercase();
1912        let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
1913        let mut ends_with_co_authors = false;
1914        let existing_co_authors = existing_text
1915            .lines()
1916            .filter_map(|line| {
1917                let line = line.trim();
1918                if line.starts_with(&lowercase_co_author_prefix) {
1919                    ends_with_co_authors = true;
1920                    Some(line)
1921                } else {
1922                    ends_with_co_authors = false;
1923                    None
1924                }
1925            })
1926            .collect::<HashSet<_>>();
1927
1928        let new_co_authors = self
1929            .potential_co_authors(cx)
1930            .into_iter()
1931            .filter(|(_, email)| {
1932                !existing_co_authors
1933                    .iter()
1934                    .any(|existing| existing.contains(email.as_str()))
1935            })
1936            .collect::<Vec<_>>();
1937
1938        if new_co_authors.is_empty() {
1939            return;
1940        }
1941
1942        if !ends_with_co_authors {
1943            message.push('\n');
1944        }
1945        for (name, email) in new_co_authors {
1946            message.push('\n');
1947            message.push_str(CO_AUTHOR_PREFIX);
1948            message.push_str(&name);
1949            message.push_str(" <");
1950            message.push_str(&email);
1951            message.push('>');
1952        }
1953        message.push('\n');
1954    }
1955
1956    fn schedule_update(
1957        &mut self,
1958        clear_pending: bool,
1959        window: &mut Window,
1960        cx: &mut Context<Self>,
1961    ) {
1962        let handle = cx.entity().downgrade();
1963        self.reopen_commit_buffer(window, cx);
1964        self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
1965            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
1966            if let Some(git_panel) = handle.upgrade() {
1967                git_panel
1968                    .update_in(&mut cx, |git_panel, _, cx| {
1969                        if clear_pending {
1970                            git_panel.clear_pending();
1971                        }
1972                        git_panel.update_visible_entries(cx);
1973                        git_panel.update_editor_placeholder(cx);
1974                    })
1975                    .ok();
1976            }
1977        });
1978    }
1979
1980    fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1981        let Some(active_repo) = self.active_repository.as_ref() else {
1982            return;
1983        };
1984        let load_buffer = active_repo.update(cx, |active_repo, cx| {
1985            let project = self.project.read(cx);
1986            active_repo.open_commit_buffer(
1987                Some(project.languages().clone()),
1988                project.buffer_store().clone(),
1989                cx,
1990            )
1991        });
1992
1993        cx.spawn_in(window, |git_panel, mut cx| async move {
1994            let buffer = load_buffer.await?;
1995            git_panel.update_in(&mut cx, |git_panel, window, cx| {
1996                if git_panel
1997                    .commit_editor
1998                    .read(cx)
1999                    .buffer()
2000                    .read(cx)
2001                    .as_singleton()
2002                    .as_ref()
2003                    != Some(&buffer)
2004                {
2005                    git_panel.commit_editor = cx.new(|cx| {
2006                        commit_message_editor(
2007                            buffer,
2008                            git_panel.suggest_commit_message().as_deref(),
2009                            git_panel.project.clone(),
2010                            true,
2011                            window,
2012                            cx,
2013                        )
2014                    });
2015                }
2016            })
2017        })
2018        .detach_and_log_err(cx);
2019    }
2020
2021    fn clear_pending(&mut self) {
2022        self.pending.retain(|v| !v.finished)
2023    }
2024
2025    fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
2026        self.entries.clear();
2027        self.single_staged_entry.take();
2028        self.single_staged_entry.take();
2029        let mut changed_entries = Vec::new();
2030        let mut new_entries = Vec::new();
2031        let mut conflict_entries = Vec::new();
2032        let mut last_staged = None;
2033        let mut staged_count = 0;
2034
2035        let Some(repo) = self.active_repository.as_ref() else {
2036            // Just clear entries if no repository is active.
2037            cx.notify();
2038            return;
2039        };
2040
2041        let repo = repo.read(cx);
2042
2043        for entry in repo.status() {
2044            let is_conflict = repo.has_conflict(&entry.repo_path);
2045            let is_new = entry.status.is_created();
2046            let staging = entry.status.staging();
2047
2048            if self.pending.iter().any(|pending| {
2049                pending.target_status == TargetStatus::Reverted
2050                    && !pending.finished
2051                    && pending
2052                        .entries
2053                        .iter()
2054                        .any(|pending| pending.repo_path == entry.repo_path)
2055            }) {
2056                continue;
2057            }
2058
2059            // dot_git_abs path always has at least one component, namely .git.
2060            let abs_path = repo
2061                .dot_git_abs_path
2062                .parent()
2063                .unwrap()
2064                .join(&entry.repo_path);
2065            let worktree_path = repo.repository_entry.unrelativize(&entry.repo_path);
2066            let entry = GitStatusEntry {
2067                repo_path: entry.repo_path.clone(),
2068                worktree_path,
2069                abs_path,
2070                status: entry.status,
2071                staging,
2072            };
2073
2074            if staging.has_staged() {
2075                staged_count += 1;
2076                last_staged = Some(entry.clone());
2077            }
2078
2079            if is_conflict {
2080                conflict_entries.push(entry);
2081            } else if is_new {
2082                new_entries.push(entry);
2083            } else {
2084                changed_entries.push(entry);
2085            }
2086        }
2087
2088        let mut pending_staged_count = 0;
2089        let mut last_pending_staged = None;
2090        let mut pending_status_for_last_staged = None;
2091        for pending in self.pending.iter() {
2092            if pending.target_status == TargetStatus::Staged {
2093                pending_staged_count += pending.entries.len();
2094                last_pending_staged = pending.entries.iter().next().cloned();
2095            }
2096            if let Some(last_staged) = &last_staged {
2097                if pending
2098                    .entries
2099                    .iter()
2100                    .any(|entry| entry.repo_path == last_staged.repo_path)
2101                {
2102                    pending_status_for_last_staged = Some(pending.target_status);
2103                }
2104            }
2105        }
2106
2107        if conflict_entries.len() == 0 && staged_count == 1 && pending_staged_count == 0 {
2108            match pending_status_for_last_staged {
2109                Some(TargetStatus::Staged) | None => {
2110                    self.single_staged_entry = last_staged;
2111                }
2112                _ => {}
2113            }
2114        } else if conflict_entries.len() == 0 && pending_staged_count == 1 {
2115            self.single_staged_entry = last_pending_staged;
2116        }
2117
2118        if conflict_entries.len() == 0 && changed_entries.len() == 1 {
2119            self.single_tracked_entry = changed_entries.first().cloned();
2120        }
2121
2122        if conflict_entries.len() > 0 {
2123            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2124                header: Section::Conflict,
2125            }));
2126            self.entries.extend(
2127                conflict_entries
2128                    .into_iter()
2129                    .map(GitListEntry::GitStatusEntry),
2130            );
2131        }
2132
2133        if changed_entries.len() > 0 {
2134            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2135                header: Section::Tracked,
2136            }));
2137            self.entries.extend(
2138                changed_entries
2139                    .into_iter()
2140                    .map(GitListEntry::GitStatusEntry),
2141            );
2142        }
2143        if new_entries.len() > 0 {
2144            self.entries.push(GitListEntry::Header(GitHeaderEntry {
2145                header: Section::New,
2146            }));
2147            self.entries
2148                .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
2149        }
2150
2151        self.update_counts(repo);
2152
2153        self.select_first_entry_if_none(cx);
2154
2155        cx.notify();
2156    }
2157
2158    fn header_state(&self, header_type: Section) -> ToggleState {
2159        let (staged_count, count) = match header_type {
2160            Section::New => (self.new_staged_count, self.new_count),
2161            Section::Tracked => (self.tracked_staged_count, self.tracked_count),
2162            Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
2163        };
2164        if staged_count == 0 {
2165            ToggleState::Unselected
2166        } else if count == staged_count {
2167            ToggleState::Selected
2168        } else {
2169            ToggleState::Indeterminate
2170        }
2171    }
2172
2173    fn update_counts(&mut self, repo: &Repository) {
2174        self.conflicted_count = 0;
2175        self.conflicted_staged_count = 0;
2176        self.new_count = 0;
2177        self.tracked_count = 0;
2178        self.new_staged_count = 0;
2179        self.tracked_staged_count = 0;
2180        self.entry_count = 0;
2181        for entry in &self.entries {
2182            let Some(status_entry) = entry.status_entry() else {
2183                continue;
2184            };
2185            self.entry_count += 1;
2186            if repo.has_conflict(&status_entry.repo_path) {
2187                self.conflicted_count += 1;
2188                if self.entry_staging(status_entry).has_staged() {
2189                    self.conflicted_staged_count += 1;
2190                }
2191            } else if status_entry.status.is_created() {
2192                self.new_count += 1;
2193                if self.entry_staging(status_entry).has_staged() {
2194                    self.new_staged_count += 1;
2195                }
2196            } else {
2197                self.tracked_count += 1;
2198                if self.entry_staging(status_entry).has_staged() {
2199                    self.tracked_staged_count += 1;
2200                }
2201            }
2202        }
2203    }
2204
2205    fn entry_staging(&self, entry: &GitStatusEntry) -> StageStatus {
2206        for pending in self.pending.iter().rev() {
2207            if pending
2208                .entries
2209                .iter()
2210                .any(|pending_entry| pending_entry.repo_path == entry.repo_path)
2211            {
2212                match pending.target_status {
2213                    TargetStatus::Staged => return StageStatus::Staged,
2214                    TargetStatus::Unstaged => return StageStatus::Unstaged,
2215                    TargetStatus::Reverted => continue,
2216                    TargetStatus::Unchanged => continue,
2217                }
2218            }
2219        }
2220        entry.staging
2221    }
2222
2223    pub(crate) fn has_staged_changes(&self) -> bool {
2224        self.tracked_staged_count > 0
2225            || self.new_staged_count > 0
2226            || self.conflicted_staged_count > 0
2227    }
2228
2229    pub(crate) fn has_unstaged_changes(&self) -> bool {
2230        self.tracked_count > self.tracked_staged_count
2231            || self.new_count > self.new_staged_count
2232            || self.conflicted_count > self.conflicted_staged_count
2233    }
2234
2235    fn has_conflicts(&self) -> bool {
2236        self.conflicted_count > 0
2237    }
2238
2239    fn has_tracked_changes(&self) -> bool {
2240        self.tracked_count > 0
2241    }
2242
2243    pub fn has_unstaged_conflicts(&self) -> bool {
2244        self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
2245    }
2246
2247    fn show_err_toast(&self, e: anyhow::Error, cx: &mut App) {
2248        let Some(workspace) = self.workspace.upgrade() else {
2249            return;
2250        };
2251        let notif_id = NotificationId::Named("git-operation-error".into());
2252
2253        let message = e.to_string().trim().to_string();
2254        let toast;
2255        if message
2256            .matches(git::repository::REMOTE_CANCELLED_BY_USER)
2257            .next()
2258            .is_some()
2259        {
2260            return; // Hide the cancelled by user message
2261        } else {
2262            toast = Toast::new(notif_id, message).on_click("Open Zed Log", |window, cx| {
2263                window.dispatch_action(workspace::OpenLog.boxed_clone(), cx);
2264            });
2265        }
2266        workspace.update(cx, |workspace, cx| {
2267            workspace.show_toast(toast, cx);
2268        });
2269    }
2270
2271    fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
2272        let Some(workspace) = self.workspace.upgrade() else {
2273            return;
2274        };
2275
2276        let notification_id = NotificationId::Named("git-remote-info".into());
2277
2278        workspace.update(cx, |workspace, cx| {
2279            workspace.show_notification(notification_id.clone(), cx, |cx| {
2280                let workspace = cx.weak_entity();
2281                cx.new(|cx| RemoteOutputToast::new(action, info, notification_id, workspace, cx))
2282            });
2283        });
2284    }
2285
2286    pub fn render_spinner(&self) -> Option<impl IntoElement> {
2287        (!self.pending_remote_operations.borrow().is_empty()).then(|| {
2288            Icon::new(IconName::ArrowCircle)
2289                .size(IconSize::XSmall)
2290                .color(Color::Info)
2291                .with_animation(
2292                    "arrow-circle",
2293                    Animation::new(Duration::from_secs(2)).repeat(),
2294                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2295                )
2296                .into_any_element()
2297        })
2298    }
2299
2300    pub fn can_commit(&self) -> bool {
2301        (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
2302    }
2303
2304    pub fn can_stage_all(&self) -> bool {
2305        self.has_unstaged_changes()
2306    }
2307
2308    pub fn can_unstage_all(&self) -> bool {
2309        self.has_staged_changes()
2310    }
2311
2312    pub(crate) fn render_generate_commit_message_button(
2313        &self,
2314        cx: &Context<Self>,
2315    ) -> Option<AnyElement> {
2316        current_language_model(cx).is_some().then(|| {
2317            if self.generate_commit_message_task.is_some() {
2318                return h_flex()
2319                    .gap_1()
2320                    .child(
2321                        Icon::new(IconName::ArrowCircle)
2322                            .size(IconSize::XSmall)
2323                            .color(Color::Info)
2324                            .with_animation(
2325                                "arrow-circle",
2326                                Animation::new(Duration::from_secs(2)).repeat(),
2327                                |icon, delta| {
2328                                    icon.transform(Transformation::rotate(percentage(delta)))
2329                                },
2330                            ),
2331                    )
2332                    .child(
2333                        Label::new("Generating Commit...")
2334                            .size(LabelSize::Small)
2335                            .color(Color::Muted),
2336                    )
2337                    .into_any_element();
2338            }
2339
2340            let can_commit = self.can_commit();
2341            let editor_focus_handle = self.commit_editor.focus_handle(cx);
2342            IconButton::new("generate-commit-message", IconName::AiEdit)
2343                .shape(ui::IconButtonShape::Square)
2344                .icon_color(Color::Muted)
2345                .tooltip(move |window, cx| {
2346                    if can_commit {
2347                        Tooltip::for_action_in(
2348                            "Generate Commit Message",
2349                            &git::GenerateCommitMessage,
2350                            &editor_focus_handle,
2351                            window,
2352                            cx,
2353                        )
2354                    } else {
2355                        Tooltip::simple(
2356                            "You must have either staged changes or tracked files to generate a commit message",
2357                            cx,
2358                        )
2359                    }
2360                })
2361                .disabled(!can_commit)
2362                .on_click(cx.listener(move |this, _event, _window, cx| {
2363                    this.generate_commit_message(cx);
2364                }))
2365                .into_any_element()
2366        })
2367    }
2368
2369    pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
2370        let potential_co_authors = self.potential_co_authors(cx);
2371        if potential_co_authors.is_empty() {
2372            None
2373        } else {
2374            Some(
2375                IconButton::new("co-authors", IconName::Person)
2376                    .shape(ui::IconButtonShape::Square)
2377                    .icon_color(Color::Disabled)
2378                    .selected_icon_color(Color::Selected)
2379                    .toggle_state(self.add_coauthors)
2380                    .tooltip(move |_, cx| {
2381                        let title = format!(
2382                            "Add co-authored-by:{}{}",
2383                            if potential_co_authors.len() == 1 {
2384                                ""
2385                            } else {
2386                                "\n"
2387                            },
2388                            potential_co_authors
2389                                .iter()
2390                                .map(|(name, email)| format!(" {} <{}>", name, email))
2391                                .join("\n")
2392                        );
2393                        Tooltip::simple(title, cx)
2394                    })
2395                    .on_click(cx.listener(|this, _, _, cx| {
2396                        this.add_coauthors = !this.add_coauthors;
2397                        cx.notify();
2398                    }))
2399                    .into_any_element(),
2400            )
2401        }
2402    }
2403
2404    pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
2405        if self.has_unstaged_conflicts() {
2406            (false, "You must resolve conflicts before committing")
2407        } else if !self.has_staged_changes() && !self.has_tracked_changes() {
2408            (
2409                false,
2410                "You must have either staged changes or tracked files to commit",
2411            )
2412        } else if self.pending_commit.is_some() {
2413            (false, "Commit in progress")
2414        } else if self.custom_or_suggested_commit_message(cx).is_none() {
2415            (false, "No commit message")
2416        } else if !self.has_write_access(cx) {
2417            (false, "You do not have write access to this project")
2418        } else {
2419            (true, self.commit_button_title())
2420        }
2421    }
2422
2423    pub fn commit_button_title(&self) -> &'static str {
2424        if self.has_staged_changes() {
2425            "Commit"
2426        } else {
2427            "Commit Tracked"
2428        }
2429    }
2430
2431    fn expand_commit_editor(
2432        &mut self,
2433        _: &git::ExpandCommitEditor,
2434        window: &mut Window,
2435        cx: &mut Context<Self>,
2436    ) {
2437        let workspace = self.workspace.clone();
2438        window.defer(cx, move |window, cx| {
2439            workspace
2440                .update(cx, |workspace, cx| {
2441                    CommitModal::toggle(workspace, window, cx)
2442                })
2443                .ok();
2444        })
2445    }
2446
2447    fn render_panel_header(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2448        let text;
2449        let action;
2450        let tooltip;
2451        if self.total_staged_count() == self.entry_count {
2452            text = "Unstage All";
2453            action = git::UnstageAll.boxed_clone();
2454            tooltip = "git reset";
2455        } else {
2456            text = "Stage All";
2457            action = git::StageAll.boxed_clone();
2458            tooltip = "git add --all ."
2459        }
2460
2461        self.panel_header_container(window, cx)
2462            .child(
2463                Button::new("diff", "Open Diff")
2464                    .tooltip(Tooltip::for_action_title_in(
2465                        "Open diff",
2466                        &Diff,
2467                        &self.focus_handle,
2468                    ))
2469                    .on_click(|_, _, cx| {
2470                        cx.defer(|cx| {
2471                            cx.dispatch_action(&Diff);
2472                        })
2473                    }),
2474            )
2475            .child(div().flex_grow()) // spacer
2476            .child(
2477                Button::new("stage-unstage-all", text)
2478                    .tooltip(Tooltip::for_action_title_in(
2479                        tooltip,
2480                        action.as_ref(),
2481                        &self.focus_handle,
2482                    ))
2483                    .on_click(move |_, _, cx| {
2484                        let action = action.boxed_clone();
2485                        cx.defer(move |cx| {
2486                            cx.dispatch_action(action.as_ref());
2487                        })
2488                    }),
2489            )
2490    }
2491
2492    pub fn render_footer(
2493        &self,
2494        window: &mut Window,
2495        cx: &mut Context<Self>,
2496    ) -> Option<impl IntoElement> {
2497        let active_repository = self.active_repository.clone()?;
2498        let (can_commit, tooltip) = self.configure_commit_button(cx);
2499        let project = self.project.clone().read(cx);
2500        let panel_editor_style = panel_editor_style(true, window, cx);
2501
2502        let enable_coauthors = self.render_co_authors(cx);
2503        let title = self.commit_button_title();
2504
2505        let editor_focus_handle = self.commit_editor.focus_handle(cx);
2506        let commit_tooltip_focus_handle = editor_focus_handle.clone();
2507        let expand_tooltip_focus_handle = editor_focus_handle.clone();
2508
2509        let branch = active_repository.read(cx).current_branch().cloned();
2510
2511        let footer_size = px(32.);
2512        let gap = px(8.0);
2513        let max_height = window.line_height() * 5. + gap + footer_size;
2514
2515        let git_panel = cx.entity().clone();
2516        let display_name = SharedString::from(Arc::from(
2517            active_repository
2518                .read(cx)
2519                .display_name(project, cx)
2520                .trim_end_matches("/"),
2521        ));
2522
2523        let footer = v_flex()
2524            .child(PanelRepoFooter::new(
2525                "footer-button",
2526                display_name,
2527                branch,
2528                Some(git_panel),
2529            ))
2530            .child(
2531                panel_editor_container(window, cx)
2532                    .id("commit-editor-container")
2533                    .relative()
2534                    .h(max_height)
2535                    .w_full()
2536                    .border_t_1()
2537                    .border_color(cx.theme().colors().border_variant)
2538                    .bg(cx.theme().colors().editor_background)
2539                    .cursor_text()
2540                    .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2541                        window.focus(&this.commit_editor.focus_handle(cx));
2542                    }))
2543                    .child(
2544                        h_flex()
2545                            .id("commit-footer")
2546                            .absolute()
2547                            .bottom_0()
2548                            .left_0()
2549                            .w_full()
2550                            .px_2()
2551                            .h(footer_size)
2552                            .flex_none()
2553                            .justify_between()
2554                            .child(
2555                                self.render_generate_commit_message_button(cx)
2556                                    .unwrap_or_else(|| div().into_any_element()),
2557                            )
2558                            .child(
2559                                h_flex().gap_0p5().children(enable_coauthors).child(
2560                                    panel_filled_button(title)
2561                                        .tooltip(move |window, cx| {
2562                                            if can_commit {
2563                                                Tooltip::for_action_in(
2564                                                    tooltip,
2565                                                    &Commit,
2566                                                    &commit_tooltip_focus_handle,
2567                                                    window,
2568                                                    cx,
2569                                                )
2570                                            } else {
2571                                                Tooltip::simple(tooltip, cx)
2572                                            }
2573                                        })
2574                                        .disabled(!can_commit || self.modal_open)
2575                                        .on_click({
2576                                            cx.listener(move |this, _: &ClickEvent, window, cx| {
2577                                                this.commit_changes(window, cx)
2578                                            })
2579                                        }),
2580                                ),
2581                            ),
2582                    )
2583                    .child(
2584                        div()
2585                            .pr_2p5()
2586                            .child(EditorElement::new(&self.commit_editor, panel_editor_style)),
2587                    )
2588                    .child(
2589                        h_flex()
2590                            .absolute()
2591                            .top_2()
2592                            .right_2()
2593                            .opacity(0.5)
2594                            .hover(|this| this.opacity(1.0))
2595                            .child(
2596                                panel_icon_button("expand-commit-editor", IconName::Maximize)
2597                                    .icon_size(IconSize::Small)
2598                                    .size(ui::ButtonSize::Default)
2599                                    .tooltip(move |window, cx| {
2600                                        Tooltip::for_action_in(
2601                                            "Open Commit Modal",
2602                                            &git::ExpandCommitEditor,
2603                                            &expand_tooltip_focus_handle,
2604                                            window,
2605                                            cx,
2606                                        )
2607                                    })
2608                                    .on_click(cx.listener({
2609                                        move |_, _, window, cx| {
2610                                            window.dispatch_action(
2611                                                git::ExpandCommitEditor.boxed_clone(),
2612                                                cx,
2613                                            )
2614                                        }
2615                                    })),
2616                            ),
2617                    ),
2618            );
2619
2620        Some(footer)
2621    }
2622
2623    fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2624        let active_repository = self.active_repository.as_ref()?;
2625        let branch = active_repository.read(cx).current_branch()?;
2626        let commit = branch.most_recent_commit.as_ref()?.clone();
2627
2628        let this = cx.entity();
2629        Some(
2630            h_flex()
2631                .items_center()
2632                .py_2()
2633                .px(px(8.))
2634                // .bg(cx.theme().colors().background)
2635                // .border_t_1()
2636                .border_color(cx.theme().colors().border)
2637                .gap_1p5()
2638                .child(
2639                    div()
2640                        .flex_grow()
2641                        .overflow_hidden()
2642                        .max_w(relative(0.6))
2643                        .h_full()
2644                        .child(
2645                            Label::new(commit.subject.clone())
2646                                .size(LabelSize::Small)
2647                                .truncate(),
2648                        )
2649                        .id("commit-msg-hover")
2650                        .hoverable_tooltip(move |window, cx| {
2651                            GitPanelMessageTooltip::new(
2652                                this.clone(),
2653                                commit.sha.clone(),
2654                                window,
2655                                cx,
2656                            )
2657                            .into()
2658                        }),
2659                )
2660                .child(div().flex_1())
2661                .child(
2662                    panel_icon_button("undo", IconName::Undo)
2663                        .icon_size(IconSize::Small)
2664                        .icon_color(Color::Muted)
2665                        .tooltip(Tooltip::for_action_title(
2666                            if self.has_staged_changes() {
2667                                "git reset HEAD^ --soft"
2668                            } else {
2669                                "git reset HEAD^"
2670                            },
2671                            &git::Uncommit,
2672                        ))
2673                        .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
2674                ),
2675        )
2676    }
2677
2678    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
2679        h_flex()
2680            .h_full()
2681            .flex_grow()
2682            .justify_center()
2683            .items_center()
2684            .child(
2685                v_flex()
2686                    .gap_3()
2687                    .child(if self.active_repository.is_some() {
2688                        "No changes to commit"
2689                    } else {
2690                        "No Git repositories"
2691                    })
2692                    .text_ui_sm(cx)
2693                    .mx_auto()
2694                    .text_color(Color::Placeholder.color(cx)),
2695            )
2696    }
2697
2698    fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2699        let scroll_bar_style = self.show_scrollbar(cx);
2700        let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
2701
2702        if !self.should_show_scrollbar(cx)
2703            || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
2704        {
2705            return None;
2706        }
2707
2708        Some(
2709            div()
2710                .id("git-panel-vertical-scroll")
2711                .occlude()
2712                .flex_none()
2713                .h_full()
2714                .cursor_default()
2715                .when(show_container, |this| this.pl_1().px_1p5())
2716                .when(!show_container, |this| {
2717                    this.absolute().right_1().top_1().bottom_1().w(px(12.))
2718                })
2719                .on_mouse_move(cx.listener(|_, _, _, cx| {
2720                    cx.notify();
2721                    cx.stop_propagation()
2722                }))
2723                .on_hover(|_, _, cx| {
2724                    cx.stop_propagation();
2725                })
2726                .on_any_mouse_down(|_, _, cx| {
2727                    cx.stop_propagation();
2728                })
2729                .on_mouse_up(
2730                    MouseButton::Left,
2731                    cx.listener(|this, _, window, cx| {
2732                        if !this.scrollbar_state.is_dragging()
2733                            && !this.focus_handle.contains_focused(window, cx)
2734                        {
2735                            this.hide_scrollbar(window, cx);
2736                            cx.notify();
2737                        }
2738
2739                        cx.stop_propagation();
2740                    }),
2741                )
2742                .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2743                    cx.notify();
2744                }))
2745                .children(Scrollbar::vertical(
2746                    // percentage as f32..end_offset as f32,
2747                    self.scrollbar_state.clone(),
2748                )),
2749        )
2750    }
2751
2752    fn render_buffer_header_controls(
2753        &self,
2754        entity: &Entity<Self>,
2755        file: &Arc<dyn File>,
2756        _: &Window,
2757        cx: &App,
2758    ) -> Option<AnyElement> {
2759        let repo = self.active_repository.as_ref()?.read(cx);
2760        let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
2761        let ix = self.entry_by_path(&repo_path)?;
2762        let entry = self.entries.get(ix)?;
2763
2764        let entry_staging = self.entry_staging(entry.status_entry()?);
2765
2766        let checkbox = Checkbox::new("stage-file", entry_staging.as_bool().into())
2767            .disabled(!self.has_write_access(cx))
2768            .fill()
2769            .elevation(ElevationIndex::Surface)
2770            .on_click({
2771                let entry = entry.clone();
2772                let git_panel = entity.downgrade();
2773                move |_, window, cx| {
2774                    git_panel
2775                        .update(cx, |this, cx| {
2776                            this.toggle_staged_for_entry(&entry, window, cx);
2777                            cx.stop_propagation();
2778                        })
2779                        .ok();
2780                }
2781            });
2782        Some(
2783            h_flex()
2784                .id("start-slot")
2785                .text_lg()
2786                .child(checkbox)
2787                .on_mouse_down(MouseButton::Left, |_, _, cx| {
2788                    // prevent the list item active state triggering when toggling checkbox
2789                    cx.stop_propagation();
2790                })
2791                .into_any_element(),
2792        )
2793    }
2794
2795    fn render_entries(
2796        &self,
2797        has_write_access: bool,
2798        _: &Window,
2799        cx: &mut Context<Self>,
2800    ) -> impl IntoElement {
2801        let entry_count = self.entries.len();
2802
2803        h_flex()
2804            .size_full()
2805            .flex_grow()
2806            .overflow_hidden()
2807            .child(
2808                uniform_list(cx.entity().clone(), "entries", entry_count, {
2809                    move |this, range, window, cx| {
2810                        let mut items = Vec::with_capacity(range.end - range.start);
2811
2812                        for ix in range {
2813                            match &this.entries.get(ix) {
2814                                Some(GitListEntry::GitStatusEntry(entry)) => {
2815                                    items.push(this.render_entry(
2816                                        ix,
2817                                        entry,
2818                                        has_write_access,
2819                                        window,
2820                                        cx,
2821                                    ));
2822                                }
2823                                Some(GitListEntry::Header(header)) => {
2824                                    items.push(this.render_list_header(
2825                                        ix,
2826                                        header,
2827                                        has_write_access,
2828                                        window,
2829                                        cx,
2830                                    ));
2831                                }
2832                                None => {}
2833                            }
2834                        }
2835
2836                        items
2837                    }
2838                })
2839                .size_full()
2840                .with_sizing_behavior(ListSizingBehavior::Auto)
2841                .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
2842                .track_scroll(self.scroll_handle.clone()),
2843            )
2844            .on_mouse_down(
2845                MouseButton::Right,
2846                cx.listener(move |this, event: &MouseDownEvent, window, cx| {
2847                    this.deploy_panel_context_menu(event.position, window, cx)
2848                }),
2849            )
2850            .children(self.render_scrollbar(cx))
2851    }
2852
2853    fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
2854        Label::new(label.into()).color(color).single_line()
2855    }
2856
2857    fn list_item_height(&self) -> Rems {
2858        rems(1.75)
2859    }
2860
2861    fn render_list_header(
2862        &self,
2863        ix: usize,
2864        header: &GitHeaderEntry,
2865        _: bool,
2866        _: &Window,
2867        _: &Context<Self>,
2868    ) -> AnyElement {
2869        let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
2870
2871        h_flex()
2872            .id(id)
2873            .h(self.list_item_height())
2874            .w_full()
2875            .items_end()
2876            .px(rems(0.75)) // ~12px
2877            .pb(rems(0.3125)) // ~ 5px
2878            .child(
2879                Label::new(header.title())
2880                    .color(Color::Muted)
2881                    .size(LabelSize::Small)
2882                    .line_height_style(LineHeightStyle::UiLabel)
2883                    .single_line(),
2884            )
2885            .into_any_element()
2886    }
2887
2888    fn load_commit_details(
2889        &self,
2890        sha: &str,
2891        cx: &mut Context<Self>,
2892    ) -> Task<anyhow::Result<CommitDetails>> {
2893        let Some(repo) = self.active_repository.clone() else {
2894            return Task::ready(Err(anyhow::anyhow!("no active repo")));
2895        };
2896        repo.update(cx, |repo, cx| {
2897            let show = repo.show(sha);
2898            cx.spawn(|_, _| async move { show.await? })
2899        })
2900    }
2901
2902    fn deploy_entry_context_menu(
2903        &mut self,
2904        position: Point<Pixels>,
2905        ix: usize,
2906        window: &mut Window,
2907        cx: &mut Context<Self>,
2908    ) {
2909        let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
2910            return;
2911        };
2912        let stage_title = if entry.status.staging().is_fully_staged() {
2913            "Unstage File"
2914        } else {
2915            "Stage File"
2916        };
2917        let restore_title = if entry.status.is_created() {
2918            "Trash File"
2919        } else {
2920            "Restore File"
2921        };
2922        let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
2923            context_menu
2924                .context(self.focus_handle.clone())
2925                .action(stage_title, ToggleStaged.boxed_clone())
2926                .action(restore_title, git::RestoreFile.boxed_clone())
2927                .separator()
2928                .action("Open Diff", Confirm.boxed_clone())
2929                .action("Open File", SecondaryConfirm.boxed_clone())
2930        });
2931        self.selected_entry = Some(ix);
2932        self.set_context_menu(context_menu, position, window, cx);
2933    }
2934
2935    fn deploy_panel_context_menu(
2936        &mut self,
2937        position: Point<Pixels>,
2938        window: &mut Window,
2939        cx: &mut Context<Self>,
2940    ) {
2941        let context_menu = git_panel_context_menu(Some(self.focus_handle.clone()), window, cx);
2942        self.set_context_menu(context_menu, position, window, cx);
2943    }
2944
2945    fn set_context_menu(
2946        &mut self,
2947        context_menu: Entity<ContextMenu>,
2948        position: Point<Pixels>,
2949        window: &Window,
2950        cx: &mut Context<Self>,
2951    ) {
2952        let subscription = cx.subscribe_in(
2953            &context_menu,
2954            window,
2955            |this, _, _: &DismissEvent, window, cx| {
2956                if this.context_menu.as_ref().is_some_and(|context_menu| {
2957                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
2958                }) {
2959                    cx.focus_self(window);
2960                }
2961                this.context_menu.take();
2962                cx.notify();
2963            },
2964        );
2965        self.context_menu = Some((context_menu, position, subscription));
2966        cx.notify();
2967    }
2968
2969    fn render_entry(
2970        &self,
2971        ix: usize,
2972        entry: &GitStatusEntry,
2973        has_write_access: bool,
2974        window: &Window,
2975        cx: &Context<Self>,
2976    ) -> AnyElement {
2977        let display_name = entry
2978            .worktree_path
2979            .file_name()
2980            .map(|name| name.to_string_lossy().into_owned())
2981            .unwrap_or_else(|| entry.worktree_path.to_string_lossy().into_owned());
2982
2983        let worktree_path = entry.worktree_path.clone();
2984        let selected = self.selected_entry == Some(ix);
2985        let marked = self.marked_entries.contains(&ix);
2986        let status_style = GitPanelSettings::get_global(cx).status_style;
2987        let status = entry.status;
2988        let has_conflict = status.is_conflicted();
2989        let is_modified = status.is_modified();
2990        let is_deleted = status.is_deleted();
2991
2992        let label_color = if status_style == StatusStyle::LabelColor {
2993            if has_conflict {
2994                Color::Conflict
2995            } else if is_modified {
2996                Color::Modified
2997            } else if is_deleted {
2998                // We don't want a bunch of red labels in the list
2999                Color::Disabled
3000            } else {
3001                Color::Created
3002            }
3003        } else {
3004            Color::Default
3005        };
3006
3007        let path_color = if status.is_deleted() {
3008            Color::Disabled
3009        } else {
3010            Color::Muted
3011        };
3012
3013        let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
3014        let checkbox_wrapper_id: ElementId =
3015            ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
3016        let checkbox_id: ElementId =
3017            ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
3018
3019        let entry_staging = self.entry_staging(entry);
3020        let mut is_staged: ToggleState = self.entry_staging(entry).as_bool().into();
3021
3022        if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
3023            is_staged = ToggleState::Selected;
3024        }
3025
3026        let handle = cx.weak_entity();
3027
3028        let selected_bg_alpha = 0.08;
3029        let marked_bg_alpha = 0.12;
3030        let state_opacity_step = 0.04;
3031
3032        let base_bg = match (selected, marked) {
3033            (true, true) => cx
3034                .theme()
3035                .status()
3036                .info
3037                .alpha(selected_bg_alpha + marked_bg_alpha),
3038            (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
3039            (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
3040            _ => cx.theme().colors().ghost_element_background,
3041        };
3042
3043        let hover_bg = if selected {
3044            cx.theme()
3045                .status()
3046                .info
3047                .alpha(selected_bg_alpha + state_opacity_step)
3048        } else {
3049            cx.theme().colors().ghost_element_hover
3050        };
3051
3052        let active_bg = if selected {
3053            cx.theme()
3054                .status()
3055                .info
3056                .alpha(selected_bg_alpha + state_opacity_step * 2.0)
3057        } else {
3058            cx.theme().colors().ghost_element_active
3059        };
3060
3061        h_flex()
3062            .id(id)
3063            .h(self.list_item_height())
3064            .w_full()
3065            .items_center()
3066            .border_1()
3067            .when(selected && self.focus_handle.is_focused(window), |el| {
3068                el.border_color(cx.theme().colors().border_focused)
3069            })
3070            .px(rems(0.75)) // ~12px
3071            .overflow_hidden()
3072            .flex_none()
3073            .gap(DynamicSpacing::Base04.rems(cx))
3074            .bg(base_bg)
3075            .hover(|this| this.bg(hover_bg))
3076            .active(|this| this.bg(active_bg))
3077            .on_click({
3078                cx.listener(move |this, event: &ClickEvent, window, cx| {
3079                    this.selected_entry = Some(ix);
3080                    cx.notify();
3081                    if event.modifiers().secondary() {
3082                        this.open_file(&Default::default(), window, cx)
3083                    } else {
3084                        this.open_diff(&Default::default(), window, cx);
3085                        this.focus_handle.focus(window);
3086                    }
3087                })
3088            })
3089            .on_mouse_down(
3090                MouseButton::Right,
3091                move |event: &MouseDownEvent, window, cx| {
3092                    // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
3093                    if event.button != MouseButton::Right {
3094                        return;
3095                    }
3096
3097                    let Some(this) = handle.upgrade() else {
3098                        return;
3099                    };
3100                    this.update(cx, |this, cx| {
3101                        this.deploy_entry_context_menu(event.position, ix, window, cx);
3102                    });
3103                    cx.stop_propagation();
3104                },
3105            )
3106            // .on_secondary_mouse_down(cx.listener(
3107            //     move |this, event: &MouseDownEvent, window, cx| {
3108            //         this.deploy_entry_context_menu(event.position, ix, window, cx);
3109            //         cx.stop_propagation();
3110            //     },
3111            // ))
3112            .child(
3113                div()
3114                    .id(checkbox_wrapper_id)
3115                    .flex_none()
3116                    .occlude()
3117                    .cursor_pointer()
3118                    .child(
3119                        Checkbox::new(checkbox_id, is_staged)
3120                            .disabled(!has_write_access)
3121                            .fill()
3122                            .placeholder(!self.has_staged_changes() && !self.has_conflicts())
3123                            .elevation(ElevationIndex::Surface)
3124                            .on_click({
3125                                let entry = entry.clone();
3126                                cx.listener(move |this, _, window, cx| {
3127                                    if !has_write_access {
3128                                        return;
3129                                    }
3130                                    this.toggle_staged_for_entry(
3131                                        &GitListEntry::GitStatusEntry(entry.clone()),
3132                                        window,
3133                                        cx,
3134                                    );
3135                                    cx.stop_propagation();
3136                                })
3137                            })
3138                            .tooltip(move |window, cx| {
3139                                let tooltip_name = if entry_staging.is_fully_staged() {
3140                                    "Unstage"
3141                                } else {
3142                                    "Stage"
3143                                };
3144
3145                                Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
3146                            }),
3147                    ),
3148            )
3149            .child(git_status_icon(status, cx))
3150            .child(
3151                h_flex()
3152                    .items_center()
3153                    .overflow_hidden()
3154                    .when_some(worktree_path.parent(), |this, parent| {
3155                        let parent_str = parent.to_string_lossy();
3156                        if !parent_str.is_empty() {
3157                            this.child(
3158                                self.entry_label(format!("{}/", parent_str), path_color)
3159                                    .when(status.is_deleted(), |this| this.strikethrough()),
3160                            )
3161                        } else {
3162                            this
3163                        }
3164                    })
3165                    .child(
3166                        self.entry_label(display_name.clone(), label_color)
3167                            .when(status.is_deleted(), |this| this.strikethrough()),
3168                    ),
3169            )
3170            .into_any_element()
3171    }
3172
3173    fn has_write_access(&self, cx: &App) -> bool {
3174        !self.project.read(cx).is_read_only(cx)
3175    }
3176}
3177
3178fn current_language_model(cx: &Context<'_, GitPanel>) -> Option<Arc<dyn LanguageModel>> {
3179    let provider = LanguageModelRegistry::read_global(cx).active_provider()?;
3180    let model = LanguageModelRegistry::read_global(cx).active_model()?;
3181    provider.is_authenticated(cx).then(|| model)
3182}
3183
3184impl Render for GitPanel {
3185    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3186        let project = self.project.read(cx);
3187        let has_entries = self.entries.len() > 0;
3188        let room = self
3189            .workspace
3190            .upgrade()
3191            .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
3192
3193        let has_write_access = self.has_write_access(cx);
3194
3195        let has_co_authors = room.map_or(false, |room| {
3196            room.read(cx)
3197                .remote_participants()
3198                .values()
3199                .any(|remote_participant| remote_participant.can_write())
3200        });
3201
3202        v_flex()
3203            .id("git_panel")
3204            .key_context(self.dispatch_context(window, cx))
3205            .track_focus(&self.focus_handle)
3206            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
3207            .when(has_write_access && !project.is_read_only(cx), |this| {
3208                this.on_action(cx.listener(Self::toggle_staged_for_selected))
3209                    .on_action(cx.listener(GitPanel::commit))
3210                    .on_action(cx.listener(Self::stage_all))
3211                    .on_action(cx.listener(Self::unstage_all))
3212                    .on_action(cx.listener(Self::stage_selected))
3213                    .on_action(cx.listener(Self::unstage_selected))
3214                    .on_action(cx.listener(Self::restore_tracked_files))
3215                    .on_action(cx.listener(Self::revert_selected))
3216                    .on_action(cx.listener(Self::clean_all))
3217                    .on_action(cx.listener(Self::generate_commit_message_action))
3218            })
3219            .on_action(cx.listener(Self::select_first))
3220            .on_action(cx.listener(Self::select_next))
3221            .on_action(cx.listener(Self::select_previous))
3222            .on_action(cx.listener(Self::select_last))
3223            .on_action(cx.listener(Self::close_panel))
3224            .on_action(cx.listener(Self::open_diff))
3225            .on_action(cx.listener(Self::open_file))
3226            .on_action(cx.listener(Self::focus_changes_list))
3227            .on_action(cx.listener(Self::focus_editor))
3228            .on_action(cx.listener(Self::expand_commit_editor))
3229            .when(has_write_access && has_co_authors, |git_panel| {
3230                git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
3231            })
3232            // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
3233            .on_hover(cx.listener(|this, hovered, window, cx| {
3234                if *hovered {
3235                    this.show_scrollbar = true;
3236                    this.hide_scrollbar_task.take();
3237                    cx.notify();
3238                } else if !this.focus_handle.contains_focused(window, cx) {
3239                    this.hide_scrollbar(window, cx);
3240                }
3241            }))
3242            .size_full()
3243            .overflow_hidden()
3244            .bg(ElevationIndex::Surface.bg(cx))
3245            .child(
3246                v_flex()
3247                    .size_full()
3248                    .child(self.render_panel_header(window, cx))
3249                    .map(|this| {
3250                        if has_entries {
3251                            this.child(self.render_entries(has_write_access, window, cx))
3252                        } else {
3253                            this.child(self.render_empty_state(cx).into_any_element())
3254                        }
3255                    })
3256                    .children(self.render_footer(window, cx))
3257                    .children(self.render_previous_commit(cx))
3258                    .into_any_element(),
3259            )
3260            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3261                deferred(
3262                    anchored()
3263                        .position(*position)
3264                        .anchor(gpui::Corner::TopLeft)
3265                        .child(menu.clone()),
3266                )
3267                .with_priority(1)
3268            }))
3269    }
3270}
3271
3272impl Focusable for GitPanel {
3273    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
3274        self.focus_handle.clone()
3275    }
3276}
3277
3278impl EventEmitter<Event> for GitPanel {}
3279
3280impl EventEmitter<PanelEvent> for GitPanel {}
3281
3282pub(crate) struct GitPanelAddon {
3283    pub(crate) workspace: WeakEntity<Workspace>,
3284}
3285
3286impl editor::Addon for GitPanelAddon {
3287    fn to_any(&self) -> &dyn std::any::Any {
3288        self
3289    }
3290
3291    fn render_buffer_header_controls(
3292        &self,
3293        excerpt_info: &ExcerptInfo,
3294        window: &Window,
3295        cx: &App,
3296    ) -> Option<AnyElement> {
3297        let file = excerpt_info.buffer.file()?;
3298        let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
3299
3300        git_panel
3301            .read(cx)
3302            .render_buffer_header_controls(&git_panel, &file, window, cx)
3303    }
3304}
3305
3306impl Panel for GitPanel {
3307    fn persistent_name() -> &'static str {
3308        "GitPanel"
3309    }
3310
3311    fn position(&self, _: &Window, cx: &App) -> DockPosition {
3312        GitPanelSettings::get_global(cx).dock
3313    }
3314
3315    fn position_is_valid(&self, position: DockPosition) -> bool {
3316        matches!(position, DockPosition::Left | DockPosition::Right)
3317    }
3318
3319    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
3320        settings::update_settings_file::<GitPanelSettings>(
3321            self.fs.clone(),
3322            cx,
3323            move |settings, _| settings.dock = Some(position),
3324        );
3325    }
3326
3327    fn size(&self, _: &Window, cx: &App) -> Pixels {
3328        self.width
3329            .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
3330    }
3331
3332    fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
3333        self.width = size;
3334        self.serialize(cx);
3335        cx.notify();
3336    }
3337
3338    fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
3339        Some(ui::IconName::GitBranchSmall).filter(|_| GitPanelSettings::get_global(cx).button)
3340    }
3341
3342    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3343        Some("Git Panel")
3344    }
3345
3346    fn toggle_action(&self) -> Box<dyn Action> {
3347        Box::new(ToggleFocus)
3348    }
3349
3350    fn activation_priority(&self) -> u32 {
3351        2
3352    }
3353}
3354
3355impl PanelHeader for GitPanel {}
3356
3357struct GitPanelMessageTooltip {
3358    commit_tooltip: Option<Entity<CommitTooltip>>,
3359}
3360
3361impl GitPanelMessageTooltip {
3362    fn new(
3363        git_panel: Entity<GitPanel>,
3364        sha: SharedString,
3365        window: &mut Window,
3366        cx: &mut App,
3367    ) -> Entity<Self> {
3368        cx.new(|cx| {
3369            cx.spawn_in(window, |this, mut cx| async move {
3370                let details = git_panel
3371                    .update(&mut cx, |git_panel, cx| {
3372                        git_panel.load_commit_details(&sha, cx)
3373                    })?
3374                    .await?;
3375
3376                let commit_details = editor::commit_tooltip::CommitDetails {
3377                    sha: details.sha.clone(),
3378                    committer_name: details.committer_name.clone(),
3379                    committer_email: details.committer_email.clone(),
3380                    commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
3381                    message: Some(editor::commit_tooltip::ParsedCommitMessage {
3382                        message: details.message.clone(),
3383                        ..Default::default()
3384                    }),
3385                };
3386
3387                this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
3388                    this.commit_tooltip =
3389                        Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
3390                    cx.notify();
3391                })
3392            })
3393            .detach();
3394
3395            Self {
3396                commit_tooltip: None,
3397            }
3398        })
3399    }
3400}
3401
3402impl Render for GitPanelMessageTooltip {
3403    fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
3404        if let Some(commit_tooltip) = &self.commit_tooltip {
3405            commit_tooltip.clone().into_any_element()
3406        } else {
3407            gpui::Empty.into_any_element()
3408        }
3409    }
3410}
3411
3412#[derive(IntoElement, IntoComponent)]
3413#[component(scope = "Version Control")]
3414pub struct PanelRepoFooter {
3415    id: SharedString,
3416    active_repository: SharedString,
3417    branch: Option<Branch>,
3418    // Getting a GitPanel in previews will be difficult.
3419    //
3420    // For now just take an option here, and we won't bind handlers to buttons in previews.
3421    git_panel: Option<Entity<GitPanel>>,
3422}
3423
3424impl PanelRepoFooter {
3425    pub fn new(
3426        id: impl Into<SharedString>,
3427        active_repository: SharedString,
3428        branch: Option<Branch>,
3429        git_panel: Option<Entity<GitPanel>>,
3430    ) -> Self {
3431        Self {
3432            id: id.into(),
3433            active_repository,
3434            branch,
3435            git_panel,
3436        }
3437    }
3438
3439    pub fn new_preview(
3440        id: impl Into<SharedString>,
3441        active_repository: SharedString,
3442        branch: Option<Branch>,
3443    ) -> Self {
3444        Self {
3445            id: id.into(),
3446            active_repository,
3447            branch,
3448            git_panel: None,
3449        }
3450    }
3451
3452    fn render_overflow_menu(&self, id: impl Into<ElementId>, cx: &App) -> impl IntoElement {
3453        let focus_handle = self
3454            .git_panel
3455            .as_ref()
3456            .map(|git_panel| git_panel.focus_handle(cx));
3457        PopoverMenu::new(id.into())
3458            .trigger(
3459                IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
3460                    .icon_size(IconSize::Small)
3461                    .icon_color(Color::Muted),
3462            )
3463            .menu(move |window, cx| Some(git_panel_context_menu(focus_handle.clone(), window, cx)))
3464            .anchor(Corner::TopRight)
3465    }
3466}
3467
3468impl RenderOnce for PanelRepoFooter {
3469    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3470        let active_repo = self.active_repository.clone();
3471        let overflow_menu_id: SharedString = format!("overflow-menu-{}", active_repo).into();
3472        let repo_selector_trigger = Button::new("repo-selector", active_repo)
3473            .style(ButtonStyle::Transparent)
3474            .size(ButtonSize::None)
3475            .label_size(LabelSize::Small)
3476            .color(Color::Muted);
3477
3478        let project = self
3479            .git_panel
3480            .as_ref()
3481            .map(|panel| panel.read(cx).project.clone());
3482
3483        let repo = self
3484            .git_panel
3485            .as_ref()
3486            .and_then(|panel| panel.read(cx).active_repository.clone());
3487
3488        let single_repo = project
3489            .as_ref()
3490            .map(|project| {
3491                filtered_repository_entries(project.read(cx).git_store().read(cx), cx).len() == 1
3492            })
3493            .unwrap_or(true);
3494
3495        let repo_selector = PopoverMenu::new("repository-switcher")
3496            .menu({
3497                let project = project.clone();
3498                move |window, cx| {
3499                    let project = project.clone()?;
3500                    Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
3501                }
3502            })
3503            .trigger_with_tooltip(
3504                repo_selector_trigger.disabled(single_repo).truncate(true),
3505                Tooltip::text("Switch active repository"),
3506            )
3507            .attach(gpui::Corner::BottomLeft)
3508            .into_any_element();
3509
3510        let branch = self.branch.clone();
3511        let branch_name = branch
3512            .as_ref()
3513            .map_or(" (no branch)".into(), |branch| branch.name.clone());
3514
3515        let branch_selector_button = Button::new("branch-selector", branch_name)
3516            .style(ButtonStyle::Transparent)
3517            .size(ButtonSize::None)
3518            .label_size(LabelSize::Small)
3519            .truncate(true)
3520            .tooltip(Tooltip::for_action_title(
3521                "Switch Branch",
3522                &zed_actions::git::Branch,
3523            ))
3524            .on_click(|_, window, cx| {
3525                window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
3526            });
3527
3528        let branch_selector = PopoverMenu::new("popover-button")
3529            .menu(move |window, cx| Some(branch_picker::popover(repo.clone(), window, cx)))
3530            .trigger_with_tooltip(
3531                branch_selector_button,
3532                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
3533            )
3534            .anchor(Corner::TopLeft)
3535            .offset(gpui::Point {
3536                x: px(0.0),
3537                y: px(-2.0),
3538            });
3539
3540        let spinner = self
3541            .git_panel
3542            .as_ref()
3543            .and_then(|git_panel| git_panel.read(cx).render_spinner());
3544
3545        h_flex()
3546            .w_full()
3547            .px_2()
3548            .h(px(36.))
3549            .items_center()
3550            .justify_between()
3551            .child(
3552                h_flex()
3553                    .flex_1()
3554                    .overflow_hidden()
3555                    .items_center()
3556                    .child(
3557                        div().child(
3558                            Icon::new(IconName::GitBranchSmall)
3559                                .size(IconSize::Small)
3560                                .color(Color::Muted),
3561                        ),
3562                    )
3563                    .child(repo_selector)
3564                    .when_some(branch.clone(), |this, _| {
3565                        this.child(
3566                            div()
3567                                .text_color(cx.theme().colors().text_muted)
3568                                .text_sm()
3569                                .child("/"),
3570                        )
3571                    })
3572                    .child(branch_selector),
3573            )
3574            .child(
3575                h_flex()
3576                    .gap_1()
3577                    .flex_shrink_0()
3578                    .children(spinner)
3579                    .child(self.render_overflow_menu(overflow_menu_id, cx))
3580                    .when_some(branch, |this, branch| {
3581                        let mut focus_handle = None;
3582                        if let Some(git_panel) = self.git_panel.as_ref() {
3583                            if !git_panel.read(cx).can_push_and_pull(cx) {
3584                                return this;
3585                            }
3586                            focus_handle = Some(git_panel.focus_handle(cx));
3587                        }
3588
3589                        this.children(render_remote_button(
3590                            self.id.clone(),
3591                            &branch,
3592                            focus_handle,
3593                            true,
3594                        ))
3595                    }),
3596            )
3597    }
3598}
3599
3600impl ComponentPreview for PanelRepoFooter {
3601    fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
3602        let unknown_upstream = None;
3603        let no_remote_upstream = Some(UpstreamTracking::Gone);
3604        let ahead_of_upstream = Some(
3605            UpstreamTrackingStatus {
3606                ahead: 2,
3607                behind: 0,
3608            }
3609            .into(),
3610        );
3611        let behind_upstream = Some(
3612            UpstreamTrackingStatus {
3613                ahead: 0,
3614                behind: 2,
3615            }
3616            .into(),
3617        );
3618        let ahead_and_behind_upstream = Some(
3619            UpstreamTrackingStatus {
3620                ahead: 3,
3621                behind: 1,
3622            }
3623            .into(),
3624        );
3625
3626        let not_ahead_or_behind_upstream = Some(
3627            UpstreamTrackingStatus {
3628                ahead: 0,
3629                behind: 0,
3630            }
3631            .into(),
3632        );
3633
3634        fn branch(upstream: Option<UpstreamTracking>) -> Branch {
3635            Branch {
3636                is_head: true,
3637                name: "some-branch".into(),
3638                upstream: upstream.map(|tracking| Upstream {
3639                    ref_name: "origin/some-branch".into(),
3640                    tracking,
3641                }),
3642                most_recent_commit: Some(CommitSummary {
3643                    sha: "abc123".into(),
3644                    subject: "Modify stuff".into(),
3645                    commit_timestamp: 1710932954,
3646                }),
3647            }
3648        }
3649
3650        fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
3651            Branch {
3652                is_head: true,
3653                name: branch_name.to_string().into(),
3654                upstream: upstream.map(|tracking| Upstream {
3655                    ref_name: format!("zed/{}", branch_name).into(),
3656                    tracking,
3657                }),
3658                most_recent_commit: Some(CommitSummary {
3659                    sha: "abc123".into(),
3660                    subject: "Modify stuff".into(),
3661                    commit_timestamp: 1710932954,
3662                }),
3663            }
3664        }
3665
3666        fn active_repository(id: usize) -> SharedString {
3667            format!("repo-{}", id).into()
3668        }
3669
3670        let example_width = px(340.);
3671
3672        v_flex()
3673            .gap_6()
3674            .w_full()
3675            .flex_none()
3676            .children(vec![example_group_with_title(
3677                "Action Button States",
3678                vec![
3679                    single_example(
3680                        "No Branch",
3681                        div()
3682                            .w(example_width)
3683                            .overflow_hidden()
3684                            .child(PanelRepoFooter::new_preview(
3685                                "no-branch",
3686                                active_repository(1).clone(),
3687                                None,
3688                            ))
3689                            .into_any_element(),
3690                    )
3691                    .grow(),
3692                    single_example(
3693                        "Remote status unknown",
3694                        div()
3695                            .w(example_width)
3696                            .overflow_hidden()
3697                            .child(PanelRepoFooter::new_preview(
3698                                "unknown-upstream",
3699                                active_repository(2).clone(),
3700                                Some(branch(unknown_upstream)),
3701                            ))
3702                            .into_any_element(),
3703                    )
3704                    .grow(),
3705                    single_example(
3706                        "No Remote Upstream",
3707                        div()
3708                            .w(example_width)
3709                            .overflow_hidden()
3710                            .child(PanelRepoFooter::new_preview(
3711                                "no-remote-upstream",
3712                                active_repository(3).clone(),
3713                                Some(branch(no_remote_upstream)),
3714                            ))
3715                            .into_any_element(),
3716                    )
3717                    .grow(),
3718                    single_example(
3719                        "Not Ahead or Behind",
3720                        div()
3721                            .w(example_width)
3722                            .overflow_hidden()
3723                            .child(PanelRepoFooter::new_preview(
3724                                "not-ahead-or-behind",
3725                                active_repository(4).clone(),
3726                                Some(branch(not_ahead_or_behind_upstream)),
3727                            ))
3728                            .into_any_element(),
3729                    )
3730                    .grow(),
3731                    single_example(
3732                        "Behind remote",
3733                        div()
3734                            .w(example_width)
3735                            .overflow_hidden()
3736                            .child(PanelRepoFooter::new_preview(
3737                                "behind-remote",
3738                                active_repository(5).clone(),
3739                                Some(branch(behind_upstream)),
3740                            ))
3741                            .into_any_element(),
3742                    )
3743                    .grow(),
3744                    single_example(
3745                        "Ahead of remote",
3746                        div()
3747                            .w(example_width)
3748                            .overflow_hidden()
3749                            .child(PanelRepoFooter::new_preview(
3750                                "ahead-of-remote",
3751                                active_repository(6).clone(),
3752                                Some(branch(ahead_of_upstream)),
3753                            ))
3754                            .into_any_element(),
3755                    )
3756                    .grow(),
3757                    single_example(
3758                        "Ahead and behind remote",
3759                        div()
3760                            .w(example_width)
3761                            .overflow_hidden()
3762                            .child(PanelRepoFooter::new_preview(
3763                                "ahead-and-behind",
3764                                active_repository(7).clone(),
3765                                Some(branch(ahead_and_behind_upstream)),
3766                            ))
3767                            .into_any_element(),
3768                    )
3769                    .grow(),
3770                ],
3771            )
3772            .grow()
3773            .vertical()])
3774            .children(vec![example_group_with_title(
3775                "Labels",
3776                vec![
3777                    single_example(
3778                        "Short Branch & Repo",
3779                        div()
3780                            .w(example_width)
3781                            .overflow_hidden()
3782                            .child(PanelRepoFooter::new_preview(
3783                                "short-branch",
3784                                SharedString::from("zed"),
3785                                Some(custom("main", behind_upstream)),
3786                            ))
3787                            .into_any_element(),
3788                    )
3789                    .grow(),
3790                    single_example(
3791                        "Long Branch",
3792                        div()
3793                            .w(example_width)
3794                            .overflow_hidden()
3795                            .child(PanelRepoFooter::new_preview(
3796                                "long-branch",
3797                                SharedString::from("zed"),
3798                                Some(custom(
3799                                    "redesign-and-update-git-ui-list-entry-style",
3800                                    behind_upstream,
3801                                )),
3802                            ))
3803                            .into_any_element(),
3804                    )
3805                    .grow(),
3806                    single_example(
3807                        "Long Repo",
3808                        div()
3809                            .w(example_width)
3810                            .overflow_hidden()
3811                            .child(PanelRepoFooter::new_preview(
3812                                "long-repo",
3813                                SharedString::from("zed-industries-community-examples"),
3814                                Some(custom("gpui", ahead_of_upstream)),
3815                            ))
3816                            .into_any_element(),
3817                    )
3818                    .grow(),
3819                    single_example(
3820                        "Long Repo & Branch",
3821                        div()
3822                            .w(example_width)
3823                            .overflow_hidden()
3824                            .child(PanelRepoFooter::new_preview(
3825                                "long-repo-and-branch",
3826                                SharedString::from("zed-industries-community-examples"),
3827                                Some(custom(
3828                                    "redesign-and-update-git-ui-list-entry-style",
3829                                    behind_upstream,
3830                                )),
3831                            ))
3832                            .into_any_element(),
3833                    )
3834                    .grow(),
3835                    single_example(
3836                        "Uppercase Repo",
3837                        div()
3838                            .w(example_width)
3839                            .overflow_hidden()
3840                            .child(PanelRepoFooter::new_preview(
3841                                "uppercase-repo",
3842                                SharedString::from("LICENSES"),
3843                                Some(custom("main", ahead_of_upstream)),
3844                            ))
3845                            .into_any_element(),
3846                    )
3847                    .grow(),
3848                    single_example(
3849                        "Uppercase Branch",
3850                        div()
3851                            .w(example_width)
3852                            .overflow_hidden()
3853                            .child(PanelRepoFooter::new_preview(
3854                                "uppercase-branch",
3855                                SharedString::from("zed"),
3856                                Some(custom("update-README", behind_upstream)),
3857                            ))
3858                            .into_any_element(),
3859                    )
3860                    .grow(),
3861                ],
3862            )
3863            .grow()
3864            .vertical()])
3865            .into_any_element()
3866    }
3867}
3868
3869#[cfg(test)]
3870mod tests {
3871    use git::status::StatusCode;
3872    use gpui::TestAppContext;
3873    use project::{FakeFs, WorktreeSettings};
3874    use serde_json::json;
3875    use settings::SettingsStore;
3876    use theme::LoadThemes;
3877    use util::path;
3878
3879    use super::*;
3880
3881    fn init_test(cx: &mut gpui::TestAppContext) {
3882        if std::env::var("RUST_LOG").is_ok() {
3883            env_logger::try_init().ok();
3884        }
3885
3886        cx.update(|cx| {
3887            let settings_store = SettingsStore::test(cx);
3888            cx.set_global(settings_store);
3889            WorktreeSettings::register(cx);
3890            workspace::init_settings(cx);
3891            theme::init(LoadThemes::JustBase, cx);
3892            language::init(cx);
3893            editor::init(cx);
3894            Project::init_settings(cx);
3895            crate::init(cx);
3896        });
3897    }
3898
3899    #[gpui::test]
3900    async fn test_entry_worktree_paths(cx: &mut TestAppContext) {
3901        init_test(cx);
3902        let fs = FakeFs::new(cx.background_executor.clone());
3903        fs.insert_tree(
3904            "/root",
3905            json!({
3906                "zed": {
3907                    ".git": {},
3908                    "crates": {
3909                        "gpui": {
3910                            "gpui.rs": "fn main() {}"
3911                        },
3912                        "util": {
3913                            "util.rs": "fn do_it() {}"
3914                        }
3915                    }
3916                },
3917            }),
3918        )
3919        .await;
3920
3921        fs.set_status_for_repo_via_git_operation(
3922            Path::new(path!("/root/zed/.git")),
3923            &[
3924                (
3925                    Path::new("crates/gpui/gpui.rs"),
3926                    StatusCode::Modified.worktree(),
3927                ),
3928                (
3929                    Path::new("crates/util/util.rs"),
3930                    StatusCode::Modified.worktree(),
3931                ),
3932            ],
3933        );
3934
3935        let project =
3936            Project::test(fs.clone(), [path!("/root/zed/crates/gpui").as_ref()], cx).await;
3937        let (workspace, cx) =
3938            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3939
3940        cx.read(|cx| {
3941            project
3942                .read(cx)
3943                .worktrees(cx)
3944                .nth(0)
3945                .unwrap()
3946                .read(cx)
3947                .as_local()
3948                .unwrap()
3949                .scan_complete()
3950        })
3951        .await;
3952
3953        cx.executor().run_until_parked();
3954
3955        let app_state = workspace.update(cx, |workspace, _| workspace.app_state().clone());
3956        let panel = cx.new_window_entity(|window, cx| {
3957            GitPanel::new(workspace.clone(), project.clone(), app_state, window, cx)
3958        });
3959
3960        let handle = cx.update_window_entity(&panel, |panel, _, _| {
3961            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
3962        });
3963        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
3964        handle.await;
3965
3966        let entries = panel.update(cx, |panel, _| panel.entries.clone());
3967        pretty_assertions::assert_eq!(
3968            entries,
3969            [
3970                GitListEntry::Header(GitHeaderEntry {
3971                    header: Section::Tracked
3972                }),
3973                GitListEntry::GitStatusEntry(GitStatusEntry {
3974                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
3975                    repo_path: "crates/gpui/gpui.rs".into(),
3976                    worktree_path: Path::new("gpui.rs").into(),
3977                    status: StatusCode::Modified.worktree(),
3978                    staging: StageStatus::Unstaged,
3979                }),
3980                GitListEntry::GitStatusEntry(GitStatusEntry {
3981                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
3982                    repo_path: "crates/util/util.rs".into(),
3983                    worktree_path: Path::new("../util/util.rs").into(),
3984                    status: StatusCode::Modified.worktree(),
3985                    staging: StageStatus::Unstaged,
3986                },),
3987            ],
3988        );
3989
3990        cx.update_window_entity(&panel, |panel, window, cx| {
3991            panel.select_last(&Default::default(), window, cx);
3992            assert_eq!(panel.selected_entry, Some(2));
3993            panel.open_diff(&Default::default(), window, cx);
3994        });
3995        cx.run_until_parked();
3996
3997        let worktree_roots = workspace.update(cx, |workspace, cx| {
3998            workspace
3999                .worktrees(cx)
4000                .map(|worktree| worktree.read(cx).abs_path())
4001                .collect::<Vec<_>>()
4002        });
4003        pretty_assertions::assert_eq!(
4004            worktree_roots,
4005            vec![
4006                Path::new(path!("/root/zed/crates/gpui")).into(),
4007                Path::new(path!("/root/zed/crates/util/util.rs")).into(),
4008            ]
4009        );
4010
4011        let repo_from_single_file_worktree = project.update(cx, |project, cx| {
4012            let git_store = project.git_store().read(cx);
4013            // The repo that comes from the single-file worktree can't be selected through the UI.
4014            let filtered_entries = filtered_repository_entries(git_store, cx)
4015                .iter()
4016                .map(|repo| repo.read(cx).worktree_abs_path.clone())
4017                .collect::<Vec<_>>();
4018            assert_eq!(
4019                filtered_entries,
4020                [Path::new(path!("/root/zed/crates/gpui")).into()]
4021            );
4022            // But we can select it artificially here.
4023            git_store
4024                .all_repositories()
4025                .into_iter()
4026                .find(|repo| {
4027                    &*repo.read(cx).worktree_abs_path
4028                        == Path::new(path!("/root/zed/crates/util/util.rs"))
4029                })
4030                .unwrap()
4031        });
4032
4033        // Paths still make sense when we somehow activate a repo that comes from a single-file worktree.
4034        repo_from_single_file_worktree.update(cx, |repo, cx| repo.activate(cx));
4035        let handle = cx.update_window_entity(&panel, |panel, _, _| {
4036            std::mem::replace(&mut panel.update_visible_entries_task, Task::ready(()))
4037        });
4038        cx.executor().advance_clock(2 * UPDATE_DEBOUNCE);
4039        handle.await;
4040        let entries = panel.update(cx, |panel, _| panel.entries.clone());
4041        pretty_assertions::assert_eq!(
4042            entries,
4043            [
4044                GitListEntry::Header(GitHeaderEntry {
4045                    header: Section::Tracked
4046                }),
4047                GitListEntry::GitStatusEntry(GitStatusEntry {
4048                    abs_path: path!("/root/zed/crates/gpui/gpui.rs").into(),
4049                    repo_path: "crates/gpui/gpui.rs".into(),
4050                    worktree_path: Path::new("../../gpui/gpui.rs").into(),
4051                    status: StatusCode::Modified.worktree(),
4052                    staging: StageStatus::Unstaged,
4053                }),
4054                GitListEntry::GitStatusEntry(GitStatusEntry {
4055                    abs_path: path!("/root/zed/crates/util/util.rs").into(),
4056                    repo_path: "crates/util/util.rs".into(),
4057                    worktree_path: Path::new("util.rs").into(),
4058                    status: StatusCode::Modified.worktree(),
4059                    staging: StageStatus::Unstaged,
4060                },),
4061            ],
4062        );
4063    }
4064}