4096 lines · 141.9 KB · Rust
RawDownload
use crate::askpass_modal::AskPassModal;use crate::commit_modal::CommitModal;use crate::git_panel_settings::StatusStyle;use crate::project_diff::Diff;use crate::remote_output_toast::{RemoteAction, RemoteOutputToast};use crate::repository_selector::filtered_repository_entries;use crate::{branch_picker, render_remote_button};use crate::{    git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,};use crate::{picker_prompt, project_diff, ProjectDiff};use anyhow::Result;use askpass::AskPassDelegate;use db::kvp::KEY_VALUE_STORE;use editor::commit_tooltip::CommitTooltip; use editor::{    scroll::ScrollbarAutoHide, Editor, EditorElement, EditorMode, EditorSettings, MultiBuffer,    ShowScrollbar,};use futures::StreamExt as _;use git::repository::{    Branch, CommitDetails, CommitSummary, DiffType, PushOptions, Remote, RemoteCommandOutput,    ResetMode, Upstream, UpstreamTracking, UpstreamTrackingStatus,};use git::status::StageStatus;use git::{repository::RepoPath, status::FileStatus, Commit, ToggleStaged};use git::{ExpandCommitEditor, RestoreTrackedFiles, StageAll, TrashUntrackedFiles, UnstageAll};use gpui::{    actions, anchored, deferred, percentage, uniform_list, Action, Animation, AnimationExt as _,    ClickEvent, Corner, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, KeyContext,    ListHorizontalSizingBehavior, ListSizingBehavior, Modifiers, ModifiersChangedEvent,    MouseButton, MouseDownEvent, Point, PromptLevel, ScrollStrategy, Stateful, Subscription, Task,    Transformation, UniformListScrollHandle, WeakEntity,};use itertools::Itertools;use language::{Buffer, File};use language_model::{    LanguageModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage, Role,};use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};use multi_buffer::ExcerptInfo;use panel::{    panel_button, panel_editor_container, panel_editor_style, panel_filled_button,    panel_icon_button, PanelHeader,};use project::{    git::{GitEvent, Repository},    Fs, Project, ProjectPath,};use serde::{Deserialize, Serialize};use settings::Settings as _;use std::cell::RefCell;use std::future::Future;use std::path::{Path, PathBuf};use std::rc::Rc;use std::{collections::HashSet, sync::Arc, time::Duration, usize};use strum::{IntoEnumIterator, VariantNames};use time::OffsetDateTime;use ui::{    prelude::*, Checkbox, ContextMenu, ElevationIndex, PopoverMenu, Scrollbar, ScrollbarState,    Tooltip,};use util::{maybe, post_inc, ResultExt, TryFutureExt};use workspace::{AppState, OpenOptions, OpenVisible}; use workspace::{    dock::{DockPosition, Panel, PanelEvent},    notifications::{DetachAndPromptErr, NotificationId},    Toast, Workspace,}; actions!(    git_panel,    [        Close,        ToggleFocus,        OpenMenu,        FocusEditor,        FocusChanges,        ToggleFillCoAuthors,        GenerateCommitMessage    ]); fn prompt<T>(    msg: &str,    detail: Option<&str>,    window: &mut Window,    cx: &mut App,) -> Task<anyhow::Result<T>>where    T: IntoEnumIterator + VariantNames + 'static,{    let rx = window.prompt(PromptLevel::Info, msg, detail, &T::VARIANTS, cx);    cx.spawn(|_| async move { Ok(T::iter().nth(rx.await?).unwrap()) })} #[derive(strum::EnumIter, strum::VariantNames)]#[strum(serialize_all = "title_case")]enum TrashCancel {    Trash,    Cancel,} fn git_panel_context_menu(    focus_handle: FocusHandle,    window: &mut Window,    cx: &mut App,) -> Entity<ContextMenu> {    ContextMenu::build(window, cx, |context_menu, _, _| {        context_menu            .context(focus_handle)            .action("Stage All", StageAll.boxed_clone())            .action("Unstage All", UnstageAll.boxed_clone())            .separator()            .action("Open Diff", project_diff::Diff.boxed_clone())            .separator()            .action("Discard Tracked Changes", RestoreTrackedFiles.boxed_clone())            .action("Trash Untracked Files", TrashUntrackedFiles.boxed_clone())    })} const GIT_PANEL_KEY: &str = "GitPanel"; const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50); pub fn init(cx: &mut App) {    cx.observe_new(        |workspace: &mut Workspace, _window, _: &mut Context<Workspace>| {            workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {                workspace.toggle_panel_focus::<GitPanel>(window, cx);            });            workspace.register_action(|workspace, _: &ExpandCommitEditor, window, cx| {                CommitModal::toggle(workspace, window, cx)            });        },    )    .detach();} #[derive(Debug, Clone)]pub enum Event {    Focus,} #[derive(Serialize, Deserialize)]struct SerializedGitPanel {    width: Option<Pixels>,} #[derive(Debug, PartialEq, Eq, Clone, Copy)]enum Section {    Conflict,    Tracked,    New,} #[derive(Debug, PartialEq, Eq, Clone)]struct GitHeaderEntry {    header: Section,} impl GitHeaderEntry {    pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {        let this = &self.header;        let status = status_entry.status;        match this {            Section::Conflict => repo.has_conflict(&status_entry.repo_path),            Section::Tracked => !status.is_created(),            Section::New => status.is_created(),        }    }    pub fn title(&self) -> &'static str {        match self.header {            Section::Conflict => "Conflicts",            Section::Tracked => "Tracked",            Section::New => "Untracked",        }    }} #[derive(Debug, PartialEq, Eq, Clone)]enum GitListEntry {    GitStatusEntry(GitStatusEntry),    Header(GitHeaderEntry),} impl GitListEntry {    fn status_entry(&self) -> Option<&GitStatusEntry> {        match self {            GitListEntry::GitStatusEntry(entry) => Some(entry),            _ => None,        }    }} #[derive(Debug, PartialEq, Eq, Clone)]pub struct GitStatusEntry {    pub(crate) repo_path: RepoPath,    pub(crate) worktree_path: Arc<Path>,    pub(crate) abs_path: PathBuf,    pub(crate) status: FileStatus,    pub(crate) staging: StageStatus,} #[derive(Clone, Copy, Debug, PartialEq, Eq)]enum TargetStatus {    Staged,    Unstaged,    Reverted,    Unchanged,} struct PendingOperation {    finished: bool,    target_status: TargetStatus,    entries: Vec<GitStatusEntry>,    op_id: usize,} type RemoteOperations = Rc<RefCell<HashSet<u32>>>; pub struct GitPanel {    remote_operation_id: u32,    pending_remote_operations: RemoteOperations,    pub(crate) active_repository: Option<Entity<Repository>>,    pub(crate) commit_editor: Entity<Editor>,    conflicted_count: usize,    conflicted_staged_count: usize,    current_modifiers: Modifiers,    add_coauthors: bool,    generate_commit_message_task: Option<Task<Option<()>>>,    entries: Vec<GitListEntry>,    single_staged_entry: Option<GitStatusEntry>,    single_tracked_entry: Option<GitStatusEntry>,    focus_handle: FocusHandle,    fs: Arc<dyn Fs>,    hide_scrollbar_task: Option<Task<()>>,    new_count: usize,    entry_count: usize,    new_staged_count: usize,    pending: Vec<PendingOperation>,    pending_commit: Option<Task<()>>,    pending_serialization: Task<Option<()>>,    pub(crate) project: Entity<Project>,    scroll_handle: UniformListScrollHandle,    scrollbar_state: ScrollbarState,    selected_entry: Option<usize>,    marked_entries: Vec<usize>,    show_scrollbar: bool,    tracked_count: usize,    tracked_staged_count: usize,    update_visible_entries_task: Task<()>,    width: Option<Pixels>,    workspace: WeakEntity<Workspace>,    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,    modal_open: bool,} struct RemoteOperationGuard {    id: u32,    pending_remote_operations: RemoteOperations,} impl Drop for RemoteOperationGuard {    fn drop(&mut self) {        self.pending_remote_operations.borrow_mut().remove(&self.id);    }} pub(crate) fn commit_message_editor(    commit_message_buffer: Entity<Buffer>,    placeholder: Option<&str>,    project: Entity<Project>,    in_panel: bool,    window: &mut Window,    cx: &mut Context<'_, Editor>,) -> Editor {    let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, cx));    let max_lines = if in_panel { 6 } else { 18 };    let mut commit_editor = Editor::new(        EditorMode::AutoHeight { max_lines },        buffer,        None,        false,        window,        cx,    );    commit_editor.set_collaboration_hub(Box::new(project));    commit_editor.set_use_autoclose(false);    commit_editor.set_show_gutter(false, cx);    commit_editor.set_show_wrap_guides(false, cx);    commit_editor.set_show_indent_guides(false, cx);    let placeholder = placeholder.unwrap_or("Enter commit message");    commit_editor.set_placeholder_text(placeholder, cx);    commit_editor} impl GitPanel {    pub fn new(        workspace: Entity<Workspace>,        project: Entity<Project>,        app_state: Arc<AppState>,        window: &mut Window,        cx: &mut Context<Self>,    ) -> Self {        let fs = app_state.fs.clone();        let git_store = project.read(cx).git_store().clone();        let active_repository = project.read(cx).active_repository(cx);        let workspace = workspace.downgrade();         let focus_handle = cx.focus_handle();        cx.on_focus(&focus_handle, window, Self::focus_in).detach();        cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {            this.hide_scrollbar(window, cx);        })        .detach();         // just to let us render a placeholder editor.        // Once the active git repo is set, this buffer will be replaced.        let temporary_buffer = cx.new(|cx| Buffer::local("", cx));        let commit_editor = cx.new(|cx| {            commit_message_editor(temporary_buffer, None, project.clone(), true, window, cx)        });         commit_editor.update(cx, |editor, cx| {            editor.clear(window, cx);        });         let scroll_handle = UniformListScrollHandle::new();         cx.subscribe_in(            &git_store,            window,            move |this, git_store, event, window, cx| match event {                GitEvent::FileSystemUpdated => {                    this.schedule_update(false, window, cx);                }                GitEvent::ActiveRepositoryChanged | GitEvent::GitStateUpdated => {                    this.active_repository = git_store.read(cx).active_repository();                    this.schedule_update(true, window, cx);                }                GitEvent::IndexWriteError(error) => {                    this.workspace                        .update(cx, |workspace, cx| {                            workspace.show_error(error, cx);                        })                        .ok();                }            },        )        .detach();         let scrollbar_state =            ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity());         let mut git_panel = Self {            pending_remote_operations: Default::default(),            remote_operation_id: 0,            active_repository,            commit_editor,            conflicted_count: 0,            conflicted_staged_count: 0,            current_modifiers: window.modifiers(),            add_coauthors: true,            generate_commit_message_task: None,            entries: Vec::new(),            focus_handle: cx.focus_handle(),            fs,            hide_scrollbar_task: None,            new_count: 0,            new_staged_count: 0,            pending: Vec::new(),            pending_commit: None,            pending_serialization: Task::ready(None),            single_staged_entry: None,            single_tracked_entry: None,            project,            scroll_handle,            scrollbar_state,            selected_entry: None,            marked_entries: Vec::new(),            show_scrollbar: false,            tracked_count: 0,            tracked_staged_count: 0,            update_visible_entries_task: Task::ready(()),            width: None,            context_menu: None,            workspace,            modal_open: false,            entry_count: 0,        };        git_panel.schedule_update(false, window, cx);        git_panel.show_scrollbar = git_panel.should_show_scrollbar(cx);        git_panel    }     pub fn entry_by_path(&self, path: &RepoPath) -> Option<usize> {        fn binary_search<F>(mut low: usize, mut high: usize, is_target: F) -> Option<usize>        where            F: Fn(usize) -> std::cmp::Ordering,        {            while low < high {                let mid = low + (high - low) / 2;                match is_target(mid) {                    std::cmp::Ordering::Equal => return Some(mid),                    std::cmp::Ordering::Less => low = mid + 1,                    std::cmp::Ordering::Greater => high = mid,                }            }            None        }        if self.conflicted_count > 0 {            let conflicted_start = 1;            if let Some(ix) = binary_search(                conflicted_start,                conflicted_start + self.conflicted_count,                |ix| {                    self.entries[ix]                        .status_entry()                        .unwrap()                        .repo_path                        .cmp(&path)                },            ) {                return Some(ix);            }        }        if self.tracked_count > 0 {            let tracked_start = if self.conflicted_count > 0 {                1 + self.conflicted_count            } else {                0            } + 1;            if let Some(ix) =                binary_search(tracked_start, tracked_start + self.tracked_count, |ix| {                    self.entries[ix]                        .status_entry()                        .unwrap()                        .repo_path                        .cmp(&path)                })            {                return Some(ix);            }        }        if self.new_count > 0 {            let untracked_start = if self.conflicted_count > 0 {                1 + self.conflicted_count            } else {                0            } + if self.tracked_count > 0 {                1 + self.tracked_count            } else {                0            } + 1;            if let Some(ix) =                binary_search(untracked_start, untracked_start + self.new_count, |ix| {                    self.entries[ix]                        .status_entry()                        .unwrap()                        .repo_path                        .cmp(&path)                })            {                return Some(ix);            }        }        None    }     pub fn select_entry_by_path(        &mut self,        path: ProjectPath,        _: &mut Window,        cx: &mut Context<Self>,    ) {        let Some(git_repo) = self.active_repository.as_ref() else {            return;        };        let Some(repo_path) = git_repo.read(cx).project_path_to_repo_path(&path) else {            return;        };        let Some(ix) = self.entry_by_path(&repo_path) else {            return;        };        self.selected_entry = Some(ix);        cx.notify();    }     fn start_remote_operation(&mut self) -> RemoteOperationGuard {        let id = post_inc(&mut self.remote_operation_id);        self.pending_remote_operations.borrow_mut().insert(id);         RemoteOperationGuard {            id,            pending_remote_operations: self.pending_remote_operations.clone(),        }    }

Lines 1–500 of 4096.