nushell/src/commands/from_yaml.rs

65 lines
2.4 KiB
Rust
Raw Normal View History

2019-06-03 09:41:28 +02:00
use crate::object::base::OF64;
2019-07-03 19:37:09 +02:00
use crate::object::{Dictionary, Primitive, Value};
2019-06-03 09:41:28 +02:00
use crate::prelude::*;
fn convert_yaml_value_to_nu_value(v: &serde_yaml::Value) -> Value {
match v {
serde_yaml::Value::Bool(b) => Value::Primitive(Primitive::Boolean(*b)),
serde_yaml::Value::Number(n) if n.is_i64() => {
Value::Primitive(Primitive::Int(n.as_i64().unwrap()))
}
serde_yaml::Value::Number(n) if n.is_f64() => {
Value::Primitive(Primitive::Float(OF64::from(n.as_f64().unwrap())))
}
2019-06-22 22:46:16 +02:00
serde_yaml::Value::String(s) => Value::string(s),
2019-06-03 09:41:28 +02:00
serde_yaml::Value::Sequence(a) => Value::List(
a.iter()
.map(|x| convert_yaml_value_to_nu_value(x))
.collect(),
),
serde_yaml::Value::Mapping(t) => {
let mut collected = Dictionary::default();
for (k, v) in t.iter() {
match k {
serde_yaml::Value::String(k) => {
2019-07-03 19:37:09 +02:00
collected.add(k.clone(), convert_yaml_value_to_nu_value(v));
2019-06-03 09:41:28 +02:00
}
_ => unimplemented!("Unknown key type"),
}
}
Value::Object(collected)
}
serde_yaml::Value::Null => Value::Primitive(Primitive::Nothing),
x => unimplemented!("Unsupported yaml case: {:?}", x),
2019-06-03 09:41:28 +02:00
}
}
2019-06-16 01:03:49 +02:00
pub fn from_yaml_string_to_value(s: String) -> serde_yaml::Result<Value> {
let v: serde_yaml::Value = serde_yaml::from_str(&s)?;
Ok(convert_yaml_value_to_nu_value(&v))
2019-06-03 09:41:28 +02:00
}
pub fn from_yaml(args: CommandArgs) -> Result<OutputStream, ShellError> {
let out = args.input;
2019-06-16 01:03:49 +02:00
let span = args.name_span;
2019-06-03 09:41:28 +02:00
Ok(out
2019-06-16 01:03:49 +02:00
.map(move |a| match a {
Value::Primitive(Primitive::String(s)) => match from_yaml_string_to_value(s) {
Ok(x) => ReturnValue::Value(x),
Err(_) => {
ReturnValue::Value(Value::Error(Box::new(ShellError::maybe_labeled_error(
"Could not parse as YAML",
"piped data failed YAML parse",
span,
))))
}
},
_ => ReturnValue::Value(Value::Error(Box::new(ShellError::maybe_labeled_error(
"Expected string values from pipeline",
"expects strings from pipeline",
span,
)))),
2019-06-03 09:41:28 +02:00
})
.boxed())
}