nushell/crates/nu-plugin-test-support/src/lib.rs
Devyn Cairns 91d44f15c1
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
2024-06-21 06:27:09 -05:00

110 lines
3.1 KiB
Rust

//! Test support for [Nushell](https://nushell.sh) plugins.
//!
//! # Example
//!
//! ```rust
//! use std::sync::Arc;
//!
//! use nu_plugin::*;
//! use nu_plugin_test_support::PluginTest;
//! use nu_protocol::{
//! Example, IntoInterruptiblePipelineData, LabeledError, PipelineData, ShellError, Signature,
//! Span, Type, Value,
//! };
//!
//! struct LowercasePlugin;
//! struct Lowercase;
//!
//! impl PluginCommand for Lowercase {
//! type Plugin = LowercasePlugin;
//!
//! fn name(&self) -> &str {
//! "lowercase"
//! }
//!
//! fn usage(&self) -> &str {
//! "Convert each string in a stream to lowercase"
//! }
//!
//! fn signature(&self) -> Signature {
//! Signature::build(self.name()).input_output_type(
//! Type::List(Type::String.into()),
//! Type::List(Type::String.into()),
//! )
//! }
//!
//! fn examples(&self) -> Vec<Example> {
//! vec![Example {
//! example: r#"[Hello wORLD] | lowercase"#,
//! description: "Lowercase a list of strings",
//! result: Some(Value::test_list(vec![
//! Value::test_string("hello"),
//! Value::test_string("world"),
//! ])),
//! }]
//! }
//!
//! fn run(
//! &self,
//! _plugin: &LowercasePlugin,
//! _engine: &EngineInterface,
//! call: &EvaluatedCall,
//! input: PipelineData,
//! ) -> Result<PipelineData, LabeledError> {
//! let span = call.head;
//! Ok(input.map(
//! move |value| {
//! value
//! .as_str()
//! .map(|string| Value::string(string.to_lowercase(), span))
//! // Errors in a stream should be returned as values.
//! .unwrap_or_else(|err| Value::error(err, span))
//! },
//! None,
//! )?)
//! }
//! }
//!
//! impl Plugin for LowercasePlugin {
//! fn version(&self) -> String {
//! env!("CARGO_PKG_VERSION").into()
//! }
//!
//! fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin=Self>>> {
//! vec![Box::new(Lowercase)]
//! }
//! }
//!
//! // #[test]
//! fn test_examples() -> Result<(), ShellError> {
//! PluginTest::new("lowercase", LowercasePlugin.into())?
//! .test_command_examples(&Lowercase)
//! }
//!
//! // #[test]
//! fn test_lowercase() -> Result<(), ShellError> {
//! let input = vec![Value::test_string("FooBar")].into_pipeline_data(Span::test_data(), None);
//! let output = PluginTest::new("lowercase", LowercasePlugin.into())?
//! .eval_with("lowercase", input)?
//! .into_value(Span::test_data())?;
//!
//! assert_eq!(
//! Value::test_list(vec![
//! Value::test_string("foobar")
//! ]),
//! output
//! );
//! Ok(())
//! }
//! #
//! # test_examples().unwrap();
//! # test_lowercase().unwrap();
//! ```
mod diff;
mod fake_persistent_plugin;
mod fake_register;
mod plugin_test;
mod spawn_fake_plugin;
pub use plugin_test::PluginTest;