3695 lines · 125.2 KB · Rust
RawDownload
use crate::branch_picker::{self};use crate::git_panel_settings::StatusStyle;use crate::remote_output_toast::{RemoteAction, RemoteOutputToast};use crate::{    git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,};use crate::{picker_prompt, project_diff, ProjectDiff};use db::kvp::KEY_VALUE_STORE;use editor::commit_tooltip::CommitTooltip; use editor::{    scroll::ScrollbarAutoHide, Editor, EditorElement, EditorMode, EditorSettings, MultiBuffer,    ShowScrollbar,};use git::repository::{    Branch, CommitDetails, CommitSummary, PushOptions, Remote, RemoteCommandOutput, ResetMode,    Upstream, UpstreamTracking, UpstreamTrackingStatus,};use git::{repository::RepoPath, status::FileStatus, Commit, ToggleStaged};use git::{RestoreTrackedFiles, StageAll, TrashUntrackedFiles, UnstageAll};use gpui::*;use itertools::Itertools;use language::{Buffer, File};use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};use multi_buffer::ExcerptInfo;use panel::{    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 smallvec::smallvec;use std::cell::RefCell;use std::future::Future;use std::rc::Rc;use std::{collections::HashSet, sync::Arc, time::Duration, usize};use strum::{IntoEnumIterator, VariantNames};use time::OffsetDateTime;use ui::{    prelude::*, ButtonLike, Checkbox, ContextMenu, ElevationIndex, PopoverMenu, Scrollbar,    ScrollbarState, Tooltip,};use util::{maybe, post_inc, ResultExt, TryFutureExt}; use workspace::{    dock::{DockPosition, Panel, PanelEvent},    notifications::{DetachAndPromptErr, NotificationId},    Toast, Workspace,}; actions!(    git_panel,    [        Close,        ToggleFocus,        OpenMenu,        FocusEditor,        FocusChanges,        ToggleFillCoAuthors,    ]); fn prompt<T>(msg: &str, detail: Option<&str>, window: &mut Window, cx: &mut App) -> Task<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(window: &mut Window, cx: &mut App) -> Entity<ContextMenu> {    ContextMenu::build(window, cx, |context_menu, _, _| {        context_menu            .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, _cx: &mut Context<Workspace>| {            workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {                workspace.toggle_panel_focus::<GitPanel>(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) status: FileStatus,    pub(crate) is_staged: Option<bool>,} #[derive(Clone, Copy, Debug, PartialEq, Eq)]enum TargetStatus {    Staged,    Unstaged,    Reverted,    Unchanged,} struct PendingOperation {    finished: bool,    target_status: TargetStatus,    repo_paths: HashSet<RepoPath>,    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,    entries: Vec<GitListEntry>,    focus_handle: FocusHandle,    fs: Arc<dyn Fs>,    hide_scrollbar_task: Option<Task<()>>,    new_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: &mut Workspace,        window: &mut Window,        cx: &mut Context<Workspace>,    ) -> Entity<Self> {        let fs = workspace.app_state().fs.clone();        let project = workspace.project().clone();        let git_store = project.read(cx).git_store().clone();        let active_repository = project.read(cx).active_repository(cx);        let workspace = cx.entity().downgrade();         cx.new(|cx| {            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);                    }                },            )            .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,                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),                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: Some(px(360.)),                context_menu: None,                workspace,                modal_open: false,            };            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(),        }    }     fn serialize(&mut self, cx: &mut Context<Self>) {        let width = self.width;        self.pending_serialization = cx.background_spawn(            async move {                KEY_VALUE_STORE                    .write_kvp(                        GIT_PANEL_KEY.into(),                        serde_json::to_string(&SerializedGitPanel { width })?,                    )                    .await?;                anyhow::Ok(())            }            .log_err(),        );    }     pub(crate) fn set_modal_open(&mut self, open: bool, cx: &mut Context<Self>) {        self.modal_open = open;        cx.notify();    }     fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {        let mut dispatch_context = KeyContext::new_with_defaults();        dispatch_context.add("GitPanel");         if self.is_focused(window, cx) {            dispatch_context.add("menu");            dispatch_context.add("ChangesList");        }         if self.commit_editor.read(cx).is_focused(window) {            dispatch_context.add("CommitEditor");        }         dispatch_context    }     fn is_focused(&self, window: &Window, cx: &Context<Self>) -> bool {        window            .focused(cx)            .map_or(false, |focused| self.focus_handle == focused)    }     fn close_panel(&mut self, _: &Close, _window: &mut Window, cx: &mut Context<Self>) {        cx.emit(PanelEvent::Close);    }     fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {

Lines 1–500 of 3695.