nu_plugin_engine/
source.rs

1use super::GetPlugin;
2use nu_protocol::{PluginIdentity, ShellError, Span};
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
41            .upgrade()
42            .ok_or_else(|| ShellError::GenericError {
43                error: format!("The `{}` plugin is no longer present", self.identity.name()),
44                msg: "removed since this object was created".into(),
45                span,
46                help: Some("try recreating the object that came from the plugin".into()),
47                inner: vec![],
48            })
49    }
50
51    /// Sources are compatible if their identities are equal
52    pub(crate) fn is_compatible(&self, other: &PluginSource) -> bool {
53        self.identity == other.identity
54    }
55}
56
57impl std::ops::Deref for PluginSource {
58    type Target = PluginIdentity;
59
60    fn deref(&self) -> &PluginIdentity {
61        &self.identity
62    }
63}