nu_protocol/plugin/registry_file/
mod.rs

1use std::{
2    io::{Read, Write},
3    path::PathBuf,
4};
5
6use serde::{Deserialize, Serialize};
7
8use crate::{PluginIdentity, PluginMetadata, PluginSignature, ShellError, Span};
9
10// This has a big impact on performance
11const BUFFER_SIZE: usize = 65536;
12
13// Chose settings at the low end, because we're just trying to get the maximum speed
14const COMPRESSION_QUALITY: u32 = 3; // 1 can be very bad
15const WIN_SIZE: u32 = 20; // recommended 20-22
16
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
18pub struct PluginRegistryFile {
19    /// The Nushell version that last updated the file.
20    pub nushell_version: String,
21
22    /// The installed plugins.
23    pub plugins: Vec<PluginRegistryItem>,
24}
25
26impl Default for PluginRegistryFile {
27    fn default() -> Self {
28        Self::new()
29    }
30}
31
32impl PluginRegistryFile {
33    /// Create a new, empty plugin registry file.
34    pub fn new() -> PluginRegistryFile {
35        PluginRegistryFile {
36            nushell_version: env!("CARGO_PKG_VERSION").to_owned(),
37            plugins: vec![],
38        }
39    }
40
41    /// Read the plugin registry file from a reader, e.g. [`File`](std::fs::File).
42    pub fn read_from(
43        reader: impl Read,
44        error_span: Option<Span>,
45    ) -> Result<PluginRegistryFile, ShellError> {
46        // Format is brotli compressed messagepack
47        let brotli_reader = brotli::Decompressor::new(reader, BUFFER_SIZE);
48
49        rmp_serde::from_read(brotli_reader).map_err(|err| ShellError::GenericError {
50            error: format!("Failed to load plugin file: {err}"),
51            msg: "plugin file load attempted here".into(),
52            span: error_span,
53            help: Some(
54                "it may be corrupt. Try deleting it and registering your plugins again".into(),
55            ),
56            inner: vec![],
57        })
58    }
59
60    /// Write the plugin registry file to a writer, e.g. [`File`](std::fs::File).
61    ///
62    /// The `nushell_version` will be updated to the current version before writing.
63    pub fn write_to(
64        &mut self,
65        writer: impl Write,
66        error_span: Option<Span>,
67    ) -> Result<(), ShellError> {
68        // Update the Nushell version before writing
69        env!("CARGO_PKG_VERSION").clone_into(&mut self.nushell_version);
70
71        // Format is brotli compressed messagepack
72        let mut brotli_writer =
73            brotli::CompressorWriter::new(writer, BUFFER_SIZE, COMPRESSION_QUALITY, WIN_SIZE);
74
75        rmp_serde::encode::write_named(&mut brotli_writer, self)
76            .map_err(|err| err.to_string())
77            .and_then(|_| brotli_writer.flush().map_err(|err| err.to_string()))
78            .map_err(|err| ShellError::GenericError {
79                error: "Failed to save plugin file".into(),
80                msg: "plugin file save attempted here".into(),
81                span: error_span,
82                help: Some(err.to_string()),
83                inner: vec![],
84            })
85    }
86
87    /// Insert or update a plugin in the plugin registry file.
88    pub fn upsert_plugin(&mut self, item: PluginRegistryItem) {
89        if let Some(existing_item) = self.plugins.iter_mut().find(|p| p.name == item.name) {
90            *existing_item = item;
91        } else {
92            self.plugins.push(item);
93
94            // Sort the plugins for consistency
95            self.plugins
96                .sort_by(|item1, item2| item1.name.cmp(&item2.name));
97        }
98    }
99}
100
101/// A single plugin definition from a [`PluginRegistryFile`].
102///
103/// Contains the information necessary for the [`PluginIdentity`], as well as possibly valid data
104/// about the plugin including the registered command signatures.
105#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
106pub struct PluginRegistryItem {
107    /// The name of the plugin, as would show in `plugin list`. This does not include the file
108    /// extension or the `nu_plugin_` prefix.
109    pub name: String,
110
111    /// The path to the file.
112    pub filename: PathBuf,
113
114    /// The shell program used to run the plugin, if applicable.
115    pub shell: Option<PathBuf>,
116
117    /// Additional data that might be invalid so that we don't fail to load the whole plugin file
118    /// if there's a deserialization error.
119    #[serde(flatten)]
120    pub data: PluginRegistryItemData,
121}
122
123impl PluginRegistryItem {
124    /// Create a [`PluginRegistryItem`] from an identity, metadata, and signatures.
125    pub fn new(
126        identity: &PluginIdentity,
127        metadata: PluginMetadata,
128        mut commands: Vec<PluginSignature>,
129    ) -> PluginRegistryItem {
130        // Sort the commands for consistency
131        commands.sort_by(|cmd1, cmd2| cmd1.sig.name.cmp(&cmd2.sig.name));
132
133        PluginRegistryItem {
134            name: identity.name().to_owned(),
135            filename: identity.filename().to_owned(),
136            shell: identity.shell().map(|p| p.to_owned()),
137            data: PluginRegistryItemData::Valid { metadata, commands },
138        }
139    }
140}
141
142/// Possibly valid data about a plugin in a [`PluginRegistryFile`]. If deserialization fails, it will
143/// be `Invalid`.
144#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
145#[serde(untagged)]
146pub enum PluginRegistryItemData {
147    Valid {
148        /// Metadata for the plugin, including its version.
149        #[serde(default)]
150        metadata: PluginMetadata,
151        /// Signatures and examples for each command provided by the plugin.
152        commands: Vec<PluginSignature>,
153    },
154    #[serde(
155        serialize_with = "serialize_invalid",
156        deserialize_with = "deserialize_invalid"
157    )]
158    Invalid,
159}
160
161fn serialize_invalid<S>(serializer: S) -> Result<S::Ok, S::Error>
162where
163    S: serde::Serializer,
164{
165    ().serialize(serializer)
166}
167
168fn deserialize_invalid<'de, D>(deserializer: D) -> Result<(), D::Error>
169where
170    D: serde::Deserializer<'de>,
171{
172    serde::de::IgnoredAny::deserialize(deserializer)?;
173    Ok(())
174}
175
176#[cfg(test)]
177mod tests;