git_panel.rs

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