added example for a config using FromValue
This commit is contained in:
parent
9b7f899410
commit
4f6c0cd8a2
|
@ -1,10 +1,37 @@
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
|
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand};
|
||||||
use nu_protocol::{Category, LabeledError, Signature, Type, Value};
|
use nu_protocol::{Category, FromValue, LabeledError, Signature, Spanned, Type, Value};
|
||||||
|
|
||||||
use crate::ExamplePlugin;
|
use crate::ExamplePlugin;
|
||||||
|
|
||||||
pub struct Config;
|
pub struct Config;
|
||||||
|
|
||||||
|
/// Example config struct.
|
||||||
|
///
|
||||||
|
/// Using the `FromValue` derive macro, structs can be easily loaded from [`Value`]s,
|
||||||
|
/// similar to serde's `Deserialize` macro.
|
||||||
|
/// This is handy for plugin configs or piped data.
|
||||||
|
/// All fields must implement [`FromValue`].
|
||||||
|
/// For [`Option`] fields, they can be omitted in the config.
|
||||||
|
///
|
||||||
|
/// This example shows that nested and spanned data work too, so you can describe nested
|
||||||
|
/// structures and get spans of values wrapped in [`Spanned`].
|
||||||
|
/// Since this config uses only `Option`s, no field is required in the config.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
#[derive(Debug, FromValue)]
|
||||||
|
struct PluginConfig {
|
||||||
|
path: Option<Spanned<PathBuf>>,
|
||||||
|
nested: Option<SubConfig>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
#[derive(Debug, FromValue)]
|
||||||
|
struct SubConfig {
|
||||||
|
bool: bool,
|
||||||
|
string: String,
|
||||||
|
}
|
||||||
|
|
||||||
impl SimplePluginCommand for Config {
|
impl SimplePluginCommand for Config {
|
||||||
type Plugin = ExamplePlugin;
|
type Plugin = ExamplePlugin;
|
||||||
|
|
||||||
|
@ -39,7 +66,11 @@ impl SimplePluginCommand for Config {
|
||||||
) -> Result<Value, LabeledError> {
|
) -> Result<Value, LabeledError> {
|
||||||
let config = engine.get_plugin_config()?;
|
let config = engine.get_plugin_config()?;
|
||||||
match config {
|
match config {
|
||||||
Some(config) => Ok(config.clone()),
|
Some(value) => {
|
||||||
|
let config = PluginConfig::from_value(value.clone())?;
|
||||||
|
println!("got config {config:?}");
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
None => Err(LabeledError::new("No config sent").with_label(
|
None => Err(LabeledError::new("No config sent").with_label(
|
||||||
"configuration for this plugin was not found in `$env.config.plugins.example`",
|
"configuration for this plugin was not found in `$env.config.plugins.example`",
|
||||||
call.head,
|
call.head,
|
||||||
|
|
Loading…
Reference in New Issue
Block a user