Add CustomValue support to plugins (#6070)

* Skeleton implementation

Lots and lots of TODOs

* Bootstrap simple CustomValue plugin support test

* Create nu_plugin_custom_value

* Skeleton for nu_plugin_custom_values

* Return a custom value from plugin

* Encode CustomValues from plugin calls as PluginResponse::PluginData

* Add new PluginCall variant CollapseCustomValue

* Handle CollapseCustomValue plugin calls

* Add CallInput::Data variant to CallInfo inputs

* Handle CallInfo with CallInput::Data plugin calls

* Send CallInput::Data if Value is PluginCustomValue from plugin calls

* Remove unnecessary boxing of plugins CallInfo

* Add fields needed to collapse PluginCustomValue to it

* Document PluginCustomValue and its purpose

* Impl collapsing using plugin calls in PluginCustomValue::to_base_value

* Implement proper typetag based deserialization for CoolCustomValue

* Test demonstrating that passing back a custom value to plugin works

* Added a failing test for describing plugin CustomValues

* Support describe for PluginCustomValues

- Add name to PluginResponse::PluginData
  - Also turn it into a struct for clarity
- Add name to PluginCustomValue
- Return name field from PluginCustomValue

* Demonstrate that plugins can create and handle multiple CustomValues

* Add bincode to nu-plugin dependencies

This is for demonstration purposes, any schemaless binary seralization
format will work. I picked bincode since it's the most popular for Rust
but there are defintely better options out there for this usecase

* serde_json::Value -> Vec<u8>

* Update capnp schema for new CallInfo.input field

* Move call_input capnp serialization and deserialization into new file

* Deserialize Value's span from Value itself instead of passing call.head

I am not sure if this was correct and I am breaking it or if it was a
bug, I don't fully understand how nu creates and uses Spans. What should
reuse spans and what should recreate new ones?
But yeah it felt weird that the Value's Span was being ignored since in
the json serializer just uses the Value's Span

* Add call_info value round trip test

* Add capnp CallInput::Data serialization and deserialization support

* Add CallInfo::CollapseCustomValue to capnp schema

* Add capnp PluginCall::CollapseCustomValue serialization and deserialization support

* Add PluginResponse::PluginData to capnp schema

* Add capnp PluginResponse::PluginData serialization and deserialization support

* Switch plugins::custom_values tests to capnp

Both json and capnp would work now! Sadly I can't choose both at the
same time :(

* Add missing JsonSerializer round trip tests

* Handle plugin returning PluginData as a response to CollapseCustomValue

* Refactor plugin calling into a reusable function

Many less levels of indentation now!

* Export PluginData from nu_plugin

So plugins can create their very own serve_plugin with whatever
CustomValue behavior they may desire

* Error if CustomValue cannot be handled by Plugin
This commit is contained in:
Mathspy
2022-07-25 12:32:56 -04:00
committed by GitHub
parent 9097e865ca
commit daa2148136
23 changed files with 1944 additions and 84 deletions

View File

@ -0,0 +1,12 @@
[package]
name = "nu_plugin_custom_values"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nu-plugin = { path = "../nu-plugin", version = "0.65.1" }
nu-protocol = { path = "../nu-protocol", version = "0.65.1", features = ["plugin"] }
serde = { version = "1.0", features = ["derive"] }
typetag = "0.1.8"

View File

@ -0,0 +1,67 @@
use nu_protocol::{CustomValue, ShellError, Span, Value};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CoolCustomValue {
pub(crate) cool: String,
}
impl CoolCustomValue {
pub fn new(content: &str) -> Self {
Self {
cool: content.to_owned(),
}
}
pub fn into_value(self, span: Span) -> Value {
Value::CustomValue {
val: Box::new(self),
span,
}
}
pub fn try_from_value(value: &Value) -> Result<Self, ShellError> {
match value {
Value::CustomValue { val, span } => match val.as_any().downcast_ref::<Self>() {
Some(cool) => Ok(cool.clone()),
None => Err(ShellError::CantConvert(
"cool".into(),
"non-cool".into(),
*span,
None,
)),
},
x => Err(ShellError::CantConvert(
"cool".into(),
x.get_type().to_string(),
x.span()?,
None,
)),
}
}
}
#[typetag::serde]
impl CustomValue for CoolCustomValue {
fn clone_value(&self, span: nu_protocol::Span) -> Value {
Value::CustomValue {
val: Box::new(self.clone()),
span,
}
}
fn value_string(&self) -> String {
self.typetag_name().to_string()
}
fn to_base_value(&self, span: nu_protocol::Span) -> Result<Value, ShellError> {
Ok(Value::String {
val: format!("I used to be a custom value! My data was ({})", self.cool),
span,
})
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}

View File

@ -0,0 +1,78 @@
mod cool_custom_value;
mod second_custom_value;
use cool_custom_value::CoolCustomValue;
use nu_plugin::{serve_plugin, CapnpSerializer, Plugin};
use nu_plugin::{EvaluatedCall, LabeledError};
use nu_protocol::{Category, ShellError, Signature, Value};
use second_custom_value::SecondCustomValue;
struct CustomValuePlugin;
impl Plugin for CustomValuePlugin {
fn signature(&self) -> Vec<nu_protocol::Signature> {
vec![
Signature::build("custom-value generate")
.usage("Signature for a plugin that generates a custom value")
.category(Category::Experimental),
Signature::build("custom-value generate2")
.usage("Signature for a plugin that generates a different custom value")
.category(Category::Experimental),
Signature::build("custom-value update")
.usage("Signature for a plugin that updates a custom value")
.category(Category::Experimental),
]
}
fn run(
&mut self,
name: &str,
call: &EvaluatedCall,
input: &Value,
) -> Result<Value, LabeledError> {
match name {
"custom-value generate" => self.generate(call, input),
"custom-value generate2" => self.generate2(call, input),
"custom-value update" => self.update(call, input),
_ => Err(LabeledError {
label: "Plugin call with wrong name signature".into(),
msg: "the signature used to call the plugin does not match any name in the plugin signature vector".into(),
span: Some(call.head),
}),
}
}
}
impl CustomValuePlugin {
fn generate(&mut self, call: &EvaluatedCall, _input: &Value) -> Result<Value, LabeledError> {
Ok(CoolCustomValue::new("abc").into_value(call.head))
}
fn generate2(&mut self, call: &EvaluatedCall, _input: &Value) -> Result<Value, LabeledError> {
Ok(SecondCustomValue::new("xyz").into_value(call.head))
}
fn update(&mut self, call: &EvaluatedCall, input: &Value) -> Result<Value, LabeledError> {
if let Ok(mut value) = CoolCustomValue::try_from_value(input) {
value.cool += "xyz";
return Ok(value.into_value(call.head));
}
if let Ok(mut value) = SecondCustomValue::try_from_value(input) {
value.something += "abc";
return Ok(value.into_value(call.head));
}
Err(ShellError::CantConvert(
"cool or second".into(),
"non-cool and non-second".into(),
call.head,
None,
)
.into())
}
}
fn main() {
serve_plugin(&mut CustomValuePlugin, CapnpSerializer {})
}

View File

@ -0,0 +1,70 @@
use nu_protocol::{CustomValue, ShellError, Span, Value};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SecondCustomValue {
pub(crate) something: String,
}
impl SecondCustomValue {
pub fn new(content: &str) -> Self {
Self {
something: content.to_owned(),
}
}
pub fn into_value(self, span: Span) -> Value {
Value::CustomValue {
val: Box::new(self),
span,
}
}
pub fn try_from_value(value: &Value) -> Result<Self, ShellError> {
match value {
Value::CustomValue { val, span } => match val.as_any().downcast_ref::<Self>() {
Some(value) => Ok(value.clone()),
None => Err(ShellError::CantConvert(
"cool".into(),
"non-cool".into(),
*span,
None,
)),
},
x => Err(ShellError::CantConvert(
"cool".into(),
x.get_type().to_string(),
x.span()?,
None,
)),
}
}
}
#[typetag::serde]
impl CustomValue for SecondCustomValue {
fn clone_value(&self, span: nu_protocol::Span) -> Value {
Value::CustomValue {
val: Box::new(self.clone()),
span,
}
}
fn value_string(&self) -> String {
self.typetag_name().to_string()
}
fn to_base_value(&self, span: nu_protocol::Span) -> Result<Value, ShellError> {
Ok(Value::String {
val: format!(
"I used to be a DIFFERENT custom value! ({})",
self.something
),
span,
})
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}