WindSoilder 055edd886d
Make plugin commands support examples. (#7984)
# Description

As title, we can't provide examples for plugin commands, this pr would
make it possible


# User-Facing Changes

Take plugin `nu-example-1` as example:
```
❯ nu-example-1 -h
PluginSignature test 1 for plugin. Returns Value::Nothing

Usage:
  > nu-example-1 {flags} <a> <b> (opt) ...(rest)

Flags:
  -h, --help - Display the help message for this command
  -f, --flag - a flag for the signature
  -n, --named <String> - named string

Parameters:
  a <int>: required integer value
  b <string>: required string value
  (optional) opt <int>: Optional number
  ...rest <string>: rest value string

Examples:
  running example with an int value and string value
  > nu-example-1 3 bb
```

The examples session is newly added.

## Basic idea behind these changes
when nushell query plugin signatures, plugin just returns it's signature
without any examples, so nushell have no idea about the examples of
plugin commands.
To adding the feature, we just making plugin returns it's signature with
examples.

Before:
```
        1. get signature
         ----------------> 
Nushell ------------------  Plugin
        <-----------------
        2. returns Vec<Signature>
```

After:
```
        1. get signature
        ----------------> 
Nushell ------------------  Plugin
        <-----------------
        2. returns Vec<PluginSignature>
```
        
When writing plugin signature to $nu.plugin-path:
Serialize `<PluginSignature>` rather than `<Signature>`, which would
enable us to serialize examples to `$nu.plugin-path`

## Shortcoming
It's a breaking changes because `Plugin::signature` is changed, and it
requires plugin authors to change their code for new signatures.

Fortunally it should be easy to change, for rust based plugin, we just
need to make a global replace from word `Signature` to word
`PluginSignature` in their plugin project.

Our content of plugin-path is really large, if one plugin have many
examples, it'd results to larger body of $nu.plugin-path, which is not
really scale. A solution would be save register information in other
binary formats rather than `json`. But I think it'd be another story.

# Tests + Formatting

Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass

# After Submitting

If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
2023-02-08 16:14:18 -06:00

318 lines
10 KiB
Rust

use itertools::Itertools;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, Spanned, Type,
Value,
};
use serde::de::Deserialize;
use std::collections::HashMap;
#[derive(Clone)]
pub struct FromYaml;
impl Command for FromYaml {
fn name(&self) -> &str {
"from yaml"
}
fn signature(&self) -> Signature {
Signature::build("from yaml")
.input_output_types(vec![(Type::String, Type::Any)])
.category(Category::Formats)
}
fn usage(&self) -> &str {
"Parse text as .yaml/.yml and create table."
}
fn examples(&self) -> Vec<Example> {
get_examples()
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
from_yaml(input, head)
}
}
#[derive(Clone)]
pub struct FromYml;
impl Command for FromYml {
fn name(&self) -> &str {
"from yml"
}
fn signature(&self) -> Signature {
Signature::build("from yml")
.input_output_types(vec![(Type::String, Type::Any)])
.category(Category::Formats)
}
fn usage(&self) -> &str {
"Parse text as .yaml/.yml and create table."
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
from_yaml(input, head)
}
fn examples(&self) -> Vec<Example> {
get_examples()
}
}
fn convert_yaml_value_to_nu_value(
v: &serde_yaml::Value,
span: Span,
val_span: Span,
) -> Result<Value, ShellError> {
let err_not_compatible_number = ShellError::UnsupportedInput(
"Expected a nu-compatible number in YAML input".to_string(),
"value originates from here".into(),
span,
val_span,
);
Ok(match v {
serde_yaml::Value::Bool(b) => Value::Bool { val: *b, span },
serde_yaml::Value::Number(n) if n.is_i64() => Value::Int {
val: n.as_i64().ok_or(err_not_compatible_number)?,
span,
},
serde_yaml::Value::Number(n) if n.is_f64() => Value::Float {
val: n.as_f64().ok_or(err_not_compatible_number)?,
span,
},
serde_yaml::Value::String(s) => Value::String {
val: s.to_string(),
span,
},
serde_yaml::Value::Sequence(a) => {
let result: Result<Vec<Value>, ShellError> = a
.iter()
.map(|x| convert_yaml_value_to_nu_value(x, span, val_span))
.collect();
Value::List {
vals: result?,
span,
}
}
serde_yaml::Value::Mapping(t) => {
let mut collected = Spanned {
item: HashMap::new(),
span,
};
for (k, v) in t {
// A ShellError that we re-use multiple times in the Mapping scenario
let err_unexpected_map = ShellError::UnsupportedInput(
format!("Unexpected YAML:\nKey: {k:?}\nValue: {v:?}"),
"value originates from here".into(),
span,
val_span,
);
match (k, v) {
(serde_yaml::Value::Number(k), _) => {
collected.item.insert(
k.to_string(),
convert_yaml_value_to_nu_value(v, span, val_span)?,
);
}
(serde_yaml::Value::Bool(k), _) => {
collected.item.insert(
k.to_string(),
convert_yaml_value_to_nu_value(v, span, val_span)?,
);
}
(serde_yaml::Value::String(k), _) => {
collected.item.insert(
k.clone(),
convert_yaml_value_to_nu_value(v, span, val_span)?,
);
}
// Hard-code fix for cases where "v" is a string without quotations with double curly braces
// e.g. k = value
// value: {{ something }}
// Strangely, serde_yaml returns
// "value" -> Mapping(Mapping { map: {Mapping(Mapping { map: {String("something"): Null} }): Null} })
(serde_yaml::Value::Mapping(m), serde_yaml::Value::Null) => {
return m
.iter()
.take(1)
.collect_vec()
.first()
.and_then(|e| match e {
(serde_yaml::Value::String(s), serde_yaml::Value::Null) => {
Some(Value::String {
val: "{{ ".to_owned() + s.as_str() + " }}",
span,
})
}
_ => None,
})
.ok_or(err_unexpected_map);
}
(_, _) => {
return Err(err_unexpected_map);
}
}
}
Value::from(collected)
}
serde_yaml::Value::Null => Value::nothing(span),
x => unimplemented!("Unsupported YAML case: {:?}", x),
})
}
pub fn from_yaml_string_to_value(
s: String,
span: Span,
val_span: Span,
) -> Result<Value, ShellError> {
let mut documents = vec![];
for document in serde_yaml::Deserializer::from_str(&s) {
let v: serde_yaml::Value = serde_yaml::Value::deserialize(document).map_err(|x| {
ShellError::UnsupportedInput(
format!("Could not load YAML: {x}"),
"value originates from here".into(),
span,
val_span,
)
})?;
documents.push(convert_yaml_value_to_nu_value(&v, span, val_span)?);
}
match documents.len() {
0 => Ok(Value::nothing(span)),
1 => Ok(documents.remove(0)),
_ => Ok(Value::List {
vals: documents,
span,
}),
}
}
pub fn get_examples() -> Vec<Example<'static>> {
vec![
Example {
example: "'a: 1' | from yaml",
description: "Converts yaml formatted string to table",
result: Some(Value::Record {
cols: vec!["a".to_string()],
vals: vec![Value::test_int(1)],
span: Span::test_data(),
}),
},
Example {
example: "'[ a: 1, b: [1, 2] ]' | from yaml",
description: "Converts yaml formatted string to table",
result: Some(Value::List {
vals: vec![
Value::Record {
cols: vec!["a".to_string()],
vals: vec![Value::test_int(1)],
span: Span::test_data(),
},
Value::Record {
cols: vec!["b".to_string()],
vals: vec![Value::List {
vals: vec![Value::test_int(1), Value::test_int(2)],
span: Span::test_data(),
}],
span: Span::test_data(),
},
],
span: Span::test_data(),
}),
},
]
}
fn from_yaml(input: PipelineData, head: Span) -> Result<PipelineData, ShellError> {
let (concat_string, span, metadata) = input.collect_string_strict(head)?;
match from_yaml_string_to_value(concat_string, head, span) {
Ok(x) => Ok(x.into_pipeline_data_with_metadata(metadata)),
Err(other) => Err(other),
}
}
#[cfg(test)]
mod test {
use super::*;
use nu_protocol::Config;
#[test]
fn test_problematic_yaml() {
struct TestCase {
description: &'static str,
input: &'static str,
expected: Result<Value, ShellError>,
}
let tt: Vec<TestCase> = vec![
TestCase {
description: "Double Curly Braces With Quotes",
input: r#"value: "{{ something }}""#,
expected: Ok(Value::Record {
cols: vec!["value".to_string()],
vals: vec![Value::test_string("{{ something }}")],
span: Span::test_data(),
}),
},
TestCase {
description: "Double Curly Braces Without Quotes",
input: r#"value: {{ something }}"#,
expected: Ok(Value::Record {
cols: vec!["value".to_string()],
vals: vec![Value::test_string("{{ something }}")],
span: Span::test_data(),
}),
},
];
let config = Config::default();
for tc in tt {
let actual = from_yaml_string_to_value(
tc.input.to_owned(),
Span::test_data(),
Span::test_data(),
);
if actual.is_err() {
assert!(
tc.expected.is_err(),
"actual is Err for test:\nTest Description {}\nErr: {:?}",
tc.description,
actual
);
} else {
assert_eq!(
actual.unwrap().into_string("", &config),
tc.expected.unwrap().into_string("", &config)
);
}
}
}
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(FromYaml {})
}
}