nushell/crates/nu_plugin_example/src/commands/generate.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

100 lines
3.1 KiB
Rust

use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, LabeledError, PipelineData, Signature,
SyntaxShape, Type, Value,
};
use crate::ExamplePlugin;
/// `example generate <initial> { |previous| {out: ..., next: ...} }`
pub struct Generate;
impl PluginCommand for Generate {
type Plugin = ExamplePlugin;
fn name(&self) -> &str {
"example generate"
}
fn usage(&self) -> &str {
"Example execution of a closure to produce a stream"
}
fn extra_usage(&self) -> &str {
"See the builtin `generate` command"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_type(Type::Nothing, Type::ListStream)
.required(
"initial",
SyntaxShape::Any,
"The initial value to pass to the closure",
)
.required(
"closure",
SyntaxShape::Closure(Some(vec![SyntaxShape::Any])),
"The closure to run to generate values",
)
.category(Category::Experimental)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
example: "example generate 0 { |i| if $i <= 10 { {out: $i, next: ($i + 2)} } }",
description: "Generate a sequence of numbers",
result: Some(Value::test_list(
[0, 2, 4, 6, 8, 10]
.into_iter()
.map(Value::test_int)
.collect(),
)),
}]
}
fn run(
&self,
_plugin: &ExamplePlugin,
engine: &EngineInterface,
call: &EvaluatedCall,
_input: PipelineData,
) -> Result<PipelineData, LabeledError> {
let engine = engine.clone();
let call = call.clone();
let initial: Value = call.req(0)?;
let closure = call.req(1)?;
let mut next = (!initial.is_nothing()).then_some(initial);
Ok(std::iter::from_fn(move || {
next.take()
.and_then(|value| {
engine
.eval_closure(&closure, vec![value.clone()], Some(value))
.and_then(|record| {
if record.is_nothing() {
Ok(None)
} else {
let record = record.as_record()?;
next = record.get("next").cloned();
Ok(record.get("out").cloned())
}
})
.transpose()
})
.map(|result| result.unwrap_or_else(|err| Value::error(err, call.head)))
})
.into_pipeline_data(None))
}
}
#[test]
fn test_examples() -> Result<(), nu_protocol::ShellError> {
use nu_cmd_lang::If;
use nu_plugin_test_support::PluginTest;
PluginTest::new("example", ExamplePlugin.into())?
.add_decl(Box::new(If))?
.test_command_examples(&Generate)
}