Allow plugins to report their own version and store it in the registry (#12883)

# Description

This allows plugins to report their version (and potentially other
metadata in the future). The version is shown in `plugin list` and in
`version`.

The metadata is stored in the registry file, and reflects whatever was
retrieved on `plugin add`, not necessarily the running binary. This can
help you to diagnose if there's some kind of mismatch with what you
expect. We could potentially use this functionality to show a warning or
error if a plugin being run does not have the same version as what was
in the cache file, suggesting `plugin add` be run again, but I haven't
done that at this point.

It is optional, and it requires the plugin author to make some code
changes if they want to provide it, since I can't automatically
determine the version of the calling crate or anything tricky like that
to do it.

Example:

```
> plugin list | select name version is_running pid
╭───┬────────────────┬─────────┬────────────┬─────╮
│ # │      name      │ version │ is_running │ pid │
├───┼────────────────┼─────────┼────────────┼─────┤
│ 0 │ example        │ 0.93.1  │ false      │     │
│ 1 │ gstat          │ 0.93.1  │ false      │     │
│ 2 │ inc            │ 0.93.1  │ false      │     │
│ 3 │ python_example │ 0.1.0   │ false      │     │
╰───┴────────────────┴─────────┴────────────┴─────╯
```

cc @maxim-uvarov (he asked for it)

# User-Facing Changes

- `plugin list` gets a `version` column
- `version` shows plugin versions when available
- plugin authors *should* add `fn metadata()` to their `impl Plugin`,
but don't have to

# Tests + Formatting

Tested the low level stuff and also the `plugin list` column.

# After Submitting
- [ ] update plugin guide docs
- [ ] update plugin protocol docs (`Metadata` call & response)
- [ ] update plugin template (`fn metadata()` should be easy)
- [ ] release notes
This commit is contained in:
Devyn Cairns
2024-06-21 04:27:09 -07:00
committed by GitHub
parent dd8f8861ed
commit 91d44f15c1
38 changed files with 360 additions and 46 deletions

View File

@ -0,0 +1,38 @@
use serde::{Deserialize, Serialize};
/// Metadata about the installed plugin. This is cached in the registry file along with the
/// signatures. None of the metadata fields are required, and more may be added in the future.
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
#[non_exhaustive]
pub struct PluginMetadata {
/// The version of the plugin itself, as self-reported.
pub version: Option<String>,
}
impl PluginMetadata {
/// Create empty metadata.
pub const fn new() -> PluginMetadata {
PluginMetadata { version: None }
}
/// Set the version of the plugin on the metadata. A suggested way to construct this is:
///
/// ```no_run
/// # use nu_protocol::PluginMetadata;
/// # fn example() -> PluginMetadata {
/// PluginMetadata::new().with_version(env!("CARGO_PKG_VERSION"))
/// # }
/// ```
///
/// which will use the version of your plugin's crate from its `Cargo.toml` file.
pub fn with_version(mut self, version: impl Into<String>) -> Self {
self.version = Some(version.into());
self
}
}
impl Default for PluginMetadata {
fn default() -> Self {
Self::new()
}
}

View File

@ -1,9 +1,11 @@
mod identity;
mod metadata;
mod registered;
mod registry_file;
mod signature;
pub use identity::*;
pub use metadata::*;
pub use registered::*;
pub use registry_file::*;
pub use signature::*;

View File

@ -1,6 +1,6 @@
use std::{any::Any, sync::Arc};
use crate::{PluginGcConfig, PluginIdentity, ShellError};
use crate::{PluginGcConfig, PluginIdentity, PluginMetadata, ShellError};
/// Trait for plugins registered in the [`EngineState`](crate::engine::EngineState).
pub trait RegisteredPlugin: Send + Sync {
@ -13,6 +13,12 @@ pub trait RegisteredPlugin: Send + Sync {
/// Process ID of the plugin executable, if running.
fn pid(&self) -> Option<u32>;
/// Get metadata for the plugin, if set.
fn metadata(&self) -> Option<PluginMetadata>;
/// Set metadata for the plugin.
fn set_metadata(&self, metadata: Option<PluginMetadata>);
/// Set garbage collection config for the plugin.
fn set_gc_config(&self, gc_config: &PluginGcConfig);

View File

@ -5,7 +5,7 @@ use std::{
use serde::{Deserialize, Serialize};
use crate::{PluginIdentity, PluginSignature, ShellError, Span};
use crate::{PluginIdentity, PluginMetadata, PluginSignature, ShellError, Span};
// This has a big impact on performance
const BUFFER_SIZE: usize = 65536;
@ -121,9 +121,10 @@ pub struct PluginRegistryItem {
}
impl PluginRegistryItem {
/// Create a [`PluginRegistryItem`] from an identity and signatures.
/// Create a [`PluginRegistryItem`] from an identity, metadata, and signatures.
pub fn new(
identity: &PluginIdentity,
metadata: PluginMetadata,
mut commands: Vec<PluginSignature>,
) -> PluginRegistryItem {
// Sort the commands for consistency
@ -133,7 +134,7 @@ impl PluginRegistryItem {
name: identity.name().to_owned(),
filename: identity.filename().to_owned(),
shell: identity.shell().map(|p| p.to_owned()),
data: PluginRegistryItemData::Valid { commands },
data: PluginRegistryItemData::Valid { metadata, commands },
}
}
}
@ -144,6 +145,9 @@ impl PluginRegistryItem {
#[serde(untagged)]
pub enum PluginRegistryItemData {
Valid {
/// Metadata for the plugin, including its version.
#[serde(default)]
metadata: PluginMetadata,
/// Signatures and examples for each command provided by the plugin.
commands: Vec<PluginSignature>,
},

View File

@ -1,6 +1,7 @@
use super::{PluginRegistryFile, PluginRegistryItem, PluginRegistryItemData};
use crate::{
Category, PluginExample, PluginSignature, ShellError, Signature, SyntaxShape, Type, Value,
Category, PluginExample, PluginMetadata, PluginSignature, ShellError, Signature, SyntaxShape,
Type, Value,
};
use pretty_assertions::assert_eq;
use std::io::Cursor;
@ -11,6 +12,9 @@ fn foo_plugin() -> PluginRegistryItem {
filename: "/path/to/nu_plugin_foo".into(),
shell: None,
data: PluginRegistryItemData::Valid {
metadata: PluginMetadata {
version: Some("0.1.0".into()),
},
commands: vec![PluginSignature {
sig: Signature::new("foo")
.input_output_type(Type::Int, Type::List(Box::new(Type::Int)))
@ -36,6 +40,9 @@ fn bar_plugin() -> PluginRegistryItem {
filename: "/path/to/nu_plugin_bar".into(),
shell: None,
data: PluginRegistryItemData::Valid {
metadata: PluginMetadata {
version: Some("0.2.0".into()),
},
commands: vec![PluginSignature {
sig: Signature::new("bar")
.usage("overwrites files with random data")