nushell/crates/nu_plugin_custom_values/src/drop_check.rs
Devyn Cairns 01d30a416b
Change PluginCommand API to be more like Command (#12279)
# Description

This is something that was discussed in the core team meeting last
Wednesday. @ayax79 is building `nu-plugin-polars` with all of the
dataframe commands into a plugin, and there are a lot of them, so it
would help to make the API more similar. At the same time, I think the
`Command` API is just better anyway. I don't think the difference is
justified, and the types for core commands have the benefit of requiring
less `.into()` because they often don't own their data

- Broke `signature()` up into `name()`, `usage()`, `extra_usage()`,
`search_terms()`, `examples()`
- `signature()` returns `nu_protocol::Signature`
- `examples()` returns `Vec<nu_protocol::Example>`
- `PluginSignature` and `PluginExample` no longer need to be used by
plugin developers

# User-Facing Changes
Breaking API for plugins yet again 😄
2024-03-27 11:59:57 +01:00

85 lines
2.1 KiB
Rust

use crate::CustomValuePlugin;
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
use nu_protocol::{
record, Category, CustomValue, LabeledError, ShellError, Signature, Span, SyntaxShape, Value,
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DropCheckValue {
pub(crate) msg: String,
}
impl DropCheckValue {
pub(crate) fn new(msg: String) -> DropCheckValue {
DropCheckValue { msg }
}
pub(crate) fn into_value(self, span: Span) -> Value {
Value::custom_value(Box::new(self), span)
}
pub(crate) fn notify(&self) {
eprintln!("DropCheckValue was dropped: {}", self.msg);
}
}
#[typetag::serde]
impl CustomValue for DropCheckValue {
fn clone_value(&self, span: Span) -> Value {
self.clone().into_value(span)
}
fn type_name(&self) -> String {
"DropCheckValue".into()
}
fn to_base_value(&self, span: Span) -> Result<Value, ShellError> {
Ok(Value::record(
record! {
"msg" => Value::string(&self.msg, span)
},
span,
))
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn notify_plugin_on_drop(&self) -> bool {
// This is what causes Nushell to let us know when the value is dropped
true
}
}
pub struct DropCheck;
impl SimplePluginCommand for DropCheck {
type Plugin = CustomValuePlugin;
fn name(&self) -> &str {
"custom-value drop-check"
}
fn usage(&self) -> &str {
"Generates a custom value that prints a message when dropped"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.required("msg", SyntaxShape::String, "the message to print on drop")
.category(Category::Experimental)
}
fn run(
&self,
_plugin: &Self::Plugin,
_engine: &EngineInterface,
call: &EvaluatedCall,
_input: &Value,
) -> Result<Value, LabeledError> {
Ok(DropCheckValue::new(call.req(0)?).into_value(call.head))
}
}