Skip to content

Instantly share code, notes, and snippets.

@cptpiepmatz
Created August 31, 2024 20:36
Show Gist options
  • Save cptpiepmatz/d5cd23b7566e0770cf0d111e31f5ed5d to your computer and use it in GitHub Desktop.
Save cptpiepmatz/d5cd23b7566e0770cf0d111e31f5ed5d to your computer and use it in GitHub Desktop.
Minimal nushell plugin that creates broken custom values by using enums.
use nu_plugin::{
serve_plugin, EngineInterface, EvaluatedCall, MsgPackSerializer, Plugin, PluginCommand,
SimplePluginCommand,
};
use nu_protocol::{CustomValue, IntoValue, LabeledError, ShellError, Signature, Span, Type, Value};
use serde::{Deserialize, Serialize};
fn main() {
serve_plugin(&BrokenValuePlugin, MsgPackSerializer)
}
struct BrokenValuePlugin;
impl Plugin for BrokenValuePlugin {
fn version(&self) -> String {
env!("CARGO_PKG_VERSION").into()
}
fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin = Self>>> {
vec![Box::new(GenBrokenValue)]
}
}
struct GenBrokenValue;
impl SimplePluginCommand for GenBrokenValue {
type Plugin = BrokenValuePlugin;
fn name(&self) -> &str {
"gen broken value"
}
fn signature(&self) -> Signature {
Signature::new(SimplePluginCommand::name(self))
.input_output_type(Type::Nothing, BrokenEnum::ty())
}
fn usage(&self) -> &str {
"generate a broken value"
}
fn run(
&self,
_: &Self::Plugin,
_: &EngineInterface,
call: &EvaluatedCall,
_: &Value,
) -> Result<Value, LabeledError> {
Ok(Value::custom(
Box::new(BrokenEnum::A(VariantA {
value: "💣".into()
})),
call.head,
))
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
enum BrokenEnum {
A(VariantA),
B(VariantB),
}
#[derive(Debug, Clone, Serialize, Deserialize, IntoValue)]
struct VariantA {
value: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, IntoValue)]
struct VariantB {
value: u32,
}
impl BrokenEnum {
fn ty() -> Type {
Type::Custom(String::from("broken-custom-value").into_boxed_str())
}
}
#[typetag::serde]
impl CustomValue for BrokenEnum {
fn clone_value(&self, span: Span) -> Value {
Value::custom(Box::new(self.clone()), span)
}
fn type_name(&self) -> String {
Self::ty().to_string()
}
fn to_base_value(&self, span: Span) -> Result<Value, ShellError> {
Ok(match self.clone() {
BrokenEnum::A(a) => a.into_value(span),
BrokenEnum::B(b) => b.into_value(span),
})
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn std::any::Any {
self
}
}
[package]
name = "nu-custom-value-broken"
version = "0.1.0-broken-custom-value"
edition = "2021"
[[bin]]
name = "nu_plugin_broken"
path = "BrokenCustomValuePlugin.rs"
[dependencies]
nu-plugin = "0.97.1"
nu-protocol = "0.97.1"
serde = { version = "1.0.209", features = ["derive"] }
typetag = "0.2.18"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment