5325 lines · 190.8 KB · Rust
RawDownload
use crate::askpass_modal::AskPassModal;use crate::commit_modal::CommitModal;use crate::commit_tooltip::CommitTooltip;use crate::commit_view::CommitView;use crate::git_panel_settings::StatusStyle;use crate::project_diff::{self, Diff, ProjectDiff};use crate::remote_output::{self, RemoteAction, SuccessMessage};use crate::{branch_picker, picker_prompt, render_remote_button};use crate::{    git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,};use agent_settings::AgentSettings;use anyhow::Context as _;use askpass::AskPassDelegate;use db::kvp::KEY_VALUE_STORE;use editor::{    Editor, EditorElement, EditorMode, EditorSettings, MultiBuffer, ShowScrollbar,    scroll::ScrollbarAutoHide,};use futures::StreamExt as _;use git::blame::ParsedCommitMessage;use git::repository::{    Branch, CommitDetails, CommitOptions, CommitSummary, DiffType, FetchOptions, GitCommitter,    PushOptions, Remote, RemoteCommandOutput, ResetMode, Upstream, UpstreamTracking,    UpstreamTrackingStatus, get_git_committer,};use git::status::StageStatus;use git::{Amend, ToggleStaged, repository::RepoPath, status::FileStatus};use git::{ExpandCommitEditor, RestoreTrackedFiles, StageAll, TrashUntrackedFiles, UnstageAll};use gpui::{    Action, Animation, AnimationExt as _, AsyncApp, AsyncWindowContext, Axis, ClickEvent, Corner,    DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, KeyContext,    ListHorizontalSizingBehavior, ListSizingBehavior, MouseButton, MouseDownEvent, Point,    PromptLevel, ScrollStrategy, Subscription, Task, Transformation, UniformListScrollHandle,    WeakEntity, actions, anchored, deferred, percentage, uniform_list,};use itertools::Itertools;use language::{Buffer, File};use language_model::{    ConfiguredModel, LanguageModel, LanguageModelRegistry, LanguageModelRequest,    LanguageModelRequestMessage, Role,};use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};use multi_buffer::ExcerptInfo;use notifications::status_toast::{StatusToast, ToastIcon};use panel::{    PanelHeader, panel_button, panel_editor_container, panel_editor_style, panel_filled_button,    panel_icon_button,};use project::git_store::{RepositoryEvent, RepositoryId};use project::{    Fs, Project, ProjectPath,    git_store::{GitStoreEvent, Repository},};use serde::{Deserialize, Serialize};use settings::{Settings as _, SettingsStore};use std::future::Future;use std::ops::Range;use std::path::{Path, PathBuf};use std::{collections::HashSet, sync::Arc, time::Duration, usize};use strum::{IntoEnumIterator, VariantNames};use time::OffsetDateTime;use ui::{    Checkbox, ContextMenu, ElevationIndex, PopoverMenu, Scrollbar, ScrollbarState, SplitButton,    Tooltip, prelude::*,};use util::{ResultExt, TryFutureExt, maybe}; use workspace::{    Workspace,    dock::{DockPosition, Panel, PanelEvent},    notifications::{DetachAndPromptErr, ErrorMessagePrompt, NotificationId},};use zed_llm_client::CompletionIntent; actions!(    git_panel,    [        /// Closes the git panel.        Close,        /// Toggles focus on the git panel.        ToggleFocus,        /// Opens the git panel menu.        OpenMenu,        /// Focuses on the commit message editor.        FocusEditor,        /// Focuses on the changes list.        FocusChanges,        /// Toggles automatic co-author suggestions.        ToggleFillCoAuthors,    ]); 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,} struct GitMenuState {    has_tracked_changes: bool,    has_staged_changes: bool,    has_unstaged_changes: bool,    has_new_changes: bool,} fn git_panel_context_menu(    focus_handle: FocusHandle,    state: GitMenuState,    window: &mut Window,    cx: &mut App,) -> Entity<ContextMenu> {    ContextMenu::build(window, cx, move |context_menu, _, _| {        context_menu            .context(focus_handle)            .action_disabled_when(                !state.has_unstaged_changes,                "Stage All",                StageAll.boxed_clone(),            )            .action_disabled_when(                !state.has_staged_changes,                "Unstage All",                UnstageAll.boxed_clone(),            )            .separator()            .action("Open Diff", project_diff::Diff.boxed_clone())            .separator()            .action_disabled_when(                !state.has_tracked_changes,                "Discard Tracked Changes",                RestoreTrackedFiles.boxed_clone(),            )            .action_disabled_when(                !state.has_new_changes,                "Trash Untracked Files",                TrashUntrackedFiles.boxed_clone(),            )    })} const GIT_PANEL_KEY: &str = "GitPanel"; const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50); pub fn register(workspace: &mut 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, None, window, cx)    });} #[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.had_conflict_on_last_merge_head_change(&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 {    Status(GitStatusEntry),    Header(GitHeaderEntry),} impl GitListEntry {    fn status_entry(&self) -> Option<&GitStatusEntry> {        match self {            GitListEntry::Status(entry) => Some(entry),            _ => None,        }    }} #[derive(Debug, PartialEq, Eq, Clone)]pub struct GitStatusEntry {    pub(crate) repo_path: RepoPath,    pub(crate) abs_path: PathBuf,    pub(crate) status: FileStatus,    pub(crate) staging: StageStatus,} impl GitStatusEntry {    fn display_name(&self) -> String {        self.repo_path            .file_name()            .map(|name| name.to_string_lossy().into_owned())            .unwrap_or_else(|| self.repo_path.to_string_lossy().into_owned())    }     fn parent_dir(&self) -> Option<String> {        self.repo_path            .parent()            .map(|parent| parent.to_string_lossy().into_owned())    }} #[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,} // computed state related to how to render scrollbars// one per axis// on render we just read this off the panel// we update it when// - settings change// - on focus in, on focus out, on hover, etc.#[derive(Debug)]struct ScrollbarProperties {    axis: Axis,    show_scrollbar: bool,    show_track: bool,    auto_hide: bool,    hide_task: Option<Task<()>>,    state: ScrollbarState,} impl ScrollbarProperties {    // Shows the scrollbar and cancels any pending hide task    fn show(&mut self, cx: &mut Context<GitPanel>) {        if !self.auto_hide {            return;        }        self.show_scrollbar = true;        self.hide_task.take();        cx.notify();    }     fn hide(&mut self, window: &mut Window, cx: &mut Context<GitPanel>) {        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);         if !self.auto_hide {            return;        }         let axis = self.axis;        self.hide_task = Some(cx.spawn_in(window, async move |panel, cx| {            cx.background_executor()                .timer(SCROLLBAR_SHOW_INTERVAL)                .await;             if let Some(panel) = panel.upgrade() {                panel                    .update(cx, |panel, cx| {                        match axis {                            Axis::Vertical => panel.vertical_scrollbar.show_scrollbar = false,                            Axis::Horizontal => panel.horizontal_scrollbar.show_scrollbar = false,                        }                        cx.notify();                    })                    .log_err();            }        }));    }} pub struct GitPanel {    pub(crate) active_repository: Option<Entity<Repository>>,    pub(crate) commit_editor: Entity<Editor>,    conflicted_count: usize,    conflicted_staged_count: usize,    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>,    horizontal_scrollbar: ScrollbarProperties,    vertical_scrollbar: ScrollbarProperties,    new_count: usize,    entry_count: usize,    new_staged_count: usize,    pending: Vec<PendingOperation>,    pending_commit: Option<Task<()>>,    amend_pending: bool,    pending_serialization: Task<Option<()>>,    pub(crate) project: Entity<Project>,    scroll_handle: UniformListScrollHandle,    max_width_item_index: Option<usize>,    selected_entry: Option<usize>,    marked_entries: Vec<usize>,    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,    show_placeholders: bool,    local_committer: Option<GitCommitter>,    local_committer_task: Option<Task<()>>,    bulk_staging: Option<BulkStaging>,    _settings_subscription: Subscription,} #[derive(Clone, Debug, PartialEq, Eq)]struct BulkStaging {    repo_id: RepositoryId,    anchor: RepoPath,} const MAX_PANEL_EDITOR_LINES: usize = 6; pub(crate) fn commit_message_editor(    commit_message_buffer: Entity<Buffer>,    placeholder: Option<SharedString>,    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 { MAX_PANEL_EDITOR_LINES } else { 18 };    let mut commit_editor = Editor::new(        EditorMode::AutoHeight {            min_lines: 1,            max_lines: Some(max_lines),        },        buffer,        None,        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_use_modal_editing(true);    commit_editor.set_show_wrap_guides(false, cx);    commit_editor.set_show_indent_guides(false, cx);    let placeholder = placeholder.unwrap_or("Enter commit message".into());    commit_editor.set_placeholder_text(placeholder, cx);    commit_editor} impl GitPanel {    fn new(        workspace: &mut Workspace,        window: &mut Window,        cx: &mut Context<Workspace>,    ) -> Entity<Self> {        let project = workspace.project().clone();        let app_state = workspace.app_state().clone();        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 git_panel = 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_scrollbars(window, cx);            })            .detach();             let mut was_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;            cx.observe_global::<SettingsStore>(move |this, cx| {                let is_sort_by_path = GitPanelSettings::get_global(cx).sort_by_path;                if is_sort_by_path != was_sort_by_path {                    this.update_visible_entries(cx);                }                was_sort_by_path = is_sort_by_path            })            .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();             let vertical_scrollbar = ScrollbarProperties {                axis: Axis::Vertical,                state: ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity()),                show_scrollbar: false,                show_track: false,                auto_hide: false,                hide_task: None,            };             let horizontal_scrollbar = ScrollbarProperties {                axis: Axis::Horizontal,                state: ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity()),                show_scrollbar: false,                show_track: false,                auto_hide: false,                hide_task: None,            };             let mut assistant_enabled = AgentSettings::get_global(cx).enabled;            let _settings_subscription = cx.observe_global::<SettingsStore>(move |_, cx| {                if assistant_enabled != AgentSettings::get_global(cx).enabled {                    assistant_enabled = AgentSettings::get_global(cx).enabled;                    cx.notify();                }            });             cx.subscribe_in(                &git_store,                window,                move |this, _git_store, event, window, cx| match event {                    GitStoreEvent::ActiveRepositoryChanged(_) => {                        this.active_repository = this.project.read(cx).active_repository(cx);                        this.schedule_update(true, window, cx);                    }                    GitStoreEvent::RepositoryUpdated(                        _,                        RepositoryEvent::Updated { full_scan, .. },                        true,                    ) => {                        this.schedule_update(*full_scan, window, cx);                    }                     GitStoreEvent::RepositoryAdded(_) | GitStoreEvent::RepositoryRemoved(_) => {                        this.schedule_update(false, window, cx);                    }                    GitStoreEvent::IndexWriteError(error) => {                        this.workspace                            .update(cx, |workspace, cx| {                                workspace.show_error(error, cx);                            })                            .ok();                    }                    GitStoreEvent::RepositoryUpdated(_, _, _) => {}                    GitStoreEvent::JobsUpdated | GitStoreEvent::ConflictsUpdated => {}                },            )            .detach();             let mut this = Self {

Lines 1–500 of 5325.