nushell/src/commands/from_toml.rs

54 lines
2.0 KiB
Rust
Raw Normal View History

2019-06-01 09:05:57 +02:00
use crate::object::base::OF64;
2019-07-03 19:37:09 +02:00
use crate::object::{Dictionary, Primitive, Value};
2019-06-01 09:05:57 +02:00
use crate::prelude::*;
fn convert_toml_value_to_nu_value(v: &toml::Value) -> Value {
match v {
toml::Value::Boolean(b) => Value::Primitive(Primitive::Boolean(*b)),
toml::Value::Integer(n) => Value::Primitive(Primitive::Int(*n)),
toml::Value::Float(n) => Value::Primitive(Primitive::Float(OF64::from(*n))),
2019-06-22 22:46:16 +02:00
toml::Value::String(s) => Value::Primitive(Primitive::String(String::from(s))),
2019-06-16 01:03:49 +02:00
toml::Value::Array(a) => Value::List(
a.iter()
2019-07-08 18:44:53 +02:00
.map(|x| convert_toml_value_to_nu_value(x).spanned_unknown())
2019-06-16 01:03:49 +02:00
.collect(),
),
2019-06-01 09:05:57 +02:00
toml::Value::Datetime(dt) => Value::Primitive(Primitive::String(dt.to_string())),
toml::Value::Table(t) => {
let mut collected = Dictionary::default();
for (k, v) in t.iter() {
2019-07-03 19:37:09 +02:00
collected.add(k.clone(), convert_toml_value_to_nu_value(v));
2019-06-01 09:05:57 +02:00
}
Value::Object(collected)
}
}
}
2019-06-16 01:03:49 +02:00
pub fn from_toml_string_to_value(s: String) -> Result<Value, Box<dyn std::error::Error>> {
let v: toml::Value = s.parse::<toml::Value>()?;
Ok(convert_toml_value_to_nu_value(&v))
2019-06-01 21:20:48 +02:00
}
2019-06-01 09:05:57 +02:00
pub fn from_toml(args: CommandArgs) -> Result<OutputStream, ShellError> {
let out = args.input;
2019-06-16 01:03:49 +02:00
let span = args.name_span;
2019-06-01 09:05:57 +02:00
Ok(out
.values
2019-07-08 18:44:53 +02:00
.map(move |a| match a.item {
2019-06-16 01:03:49 +02:00
Value::Primitive(Primitive::String(s)) => match from_toml_string_to_value(s) {
2019-07-08 18:44:53 +02:00
Ok(x) => ReturnSuccess::value(x.spanned(a.span)),
Err(_) => Err(ShellError::maybe_labeled_error(
"Could not parse as TOML",
"piped data failed TOML parse",
span,
)),
2019-06-16 01:03:49 +02:00
},
_ => Err(ShellError::maybe_labeled_error(
2019-06-16 01:03:49 +02:00
"Expected string values from pipeline",
"expects strings from pipeline",
span,
)),
2019-06-01 09:05:57 +02:00
})
.to_output_stream())
2019-06-01 09:05:57 +02:00
}