Skip to main content

nu_plugin_engine/
source.rs

1use super::GetPlugin;
2use nu_protocol::{PluginIdentity, ShellError, Span, shell_error::generic::GenericError};
3use std::sync::{Arc, Weak};
4
5/// The source of a custom value or plugin command. Includes a weak reference to the persistent
6/// plugin so it can be retrieved.
7#[derive(Debug, Clone)]
8pub struct PluginSource {
9    /// The identity of the plugin
10    pub(crate) identity: Arc<PluginIdentity>,
11    /// A weak reference to the persistent plugin that might hold an interface to the plugin.
12    ///
13    /// This is weak to avoid cyclic references, but it does mean we might fail to upgrade if
14    /// the engine state lost the [`PersistentPlugin`][crate::PersistentPlugin] at some point.
15    pub(crate) persistent: Weak<dyn GetPlugin>,
16}
17
18impl PluginSource {
19    /// Create from an implementation of `GetPlugin`
20    pub fn new(plugin: Arc<dyn GetPlugin>) -> PluginSource {
21        PluginSource {
22            identity: plugin.identity().clone().into(),
23            persistent: Arc::downgrade(&plugin),
24        }
25    }
26
27    /// Create a new fake source with a fake identity, for testing
28    ///
29    /// Warning: [`.persistent()`](Self::persistent) will always return an error.
30    pub fn new_fake(name: &str) -> PluginSource {
31        PluginSource {
32            identity: PluginIdentity::new_fake(name).into(),
33            persistent: Weak::<crate::PersistentPlugin>::new(),
34        }
35    }
36
37    /// Try to upgrade the persistent reference, and return an error referencing `span` as the
38    /// object that referenced it otherwise
39    pub fn persistent(&self, span: Option<Span>) -> Result<Arc<dyn GetPlugin>, ShellError> {
40        self.persistent.upgrade().ok_or_else(|| {
41            let error = if let Some(span) = span {
42                GenericError::new(
43                    format!("The `{}` plugin is no longer present", self.identity.name()),
44                    "removed since this object was created",
45                    span,
46                )
47                .with_help("try recreating the object that came from the plugin")
48            } else {
49                GenericError::new_internal(
50                    format!("The `{}` plugin is no longer present", self.identity.name()),
51                    "removed since this object was created",
52                )
53                .with_help("try recreating the object that came from the plugin")
54            };
55            ShellError::Generic(error)
56        })
57    }
58
59    /// Sources are compatible if their identities are equal
60    pub(crate) fn is_compatible(&self, other: &PluginSource) -> bool {
61        self.identity == other.identity
62    }
63}
64
65impl std::ops::Deref for PluginSource {
66    type Target = PluginIdentity;
67
68    fn deref(&self) -> &PluginIdentity {
69        &self.identity
70    }
71}