nushell/src/commands/from_ini.rs

51 lines
1.7 KiB
Rust
Raw Normal View History

2019-07-03 19:37:09 +02:00
use crate::object::{Dictionary, Primitive, Value};
2019-06-16 08:43:40 +02:00
use crate::prelude::*;
use indexmap::IndexMap;
use std::collections::HashMap;
fn convert_ini_second_to_nu_value(v: &HashMap<String, String>) -> Value {
let mut second = Dictionary::new(IndexMap::new());
for (key, value) in v.into_iter() {
second.add(
2019-07-03 19:37:09 +02:00
key.clone(),
2019-06-16 08:43:40 +02:00
Value::Primitive(Primitive::String(value.clone())),
);
}
Value::Object(second)
}
fn convert_ini_top_to_nu_value(v: &HashMap<String, HashMap<String, String>>) -> Value {
let mut top_level = Dictionary::new(IndexMap::new());
for (key, value) in v.iter() {
2019-07-03 19:37:09 +02:00
top_level.add(key.clone(), convert_ini_second_to_nu_value(value));
2019-06-16 08:43:40 +02:00
}
Value::Object(top_level)
}
pub fn from_ini_string_to_value(s: String) -> Result<Value, Box<dyn std::error::Error>> {
let v: HashMap<String, HashMap<String, String>> = serde_ini::from_str(&s)?;
Ok(convert_ini_top_to_nu_value(&v))
}
pub fn from_ini(args: CommandArgs) -> Result<OutputStream, ShellError> {
let out = args.input;
let span = args.name_span;
Ok(out
.values
2019-06-16 08:43:40 +02:00
.map(move |a| match a {
Value::Primitive(Primitive::String(s)) => match from_ini_string_to_value(s) {
Ok(x) => Ok(ReturnSuccess::Value(x)),
Err(e) => Err(ShellError::maybe_labeled_error(
"Could not parse as INI",
format!("{:#?}", e),
span,
)),
2019-06-16 08:43:40 +02:00
},
_ => Err(ShellError::maybe_labeled_error(
2019-06-16 08:43:40 +02:00
"Expected string values from pipeline",
"expects strings from pipeline",
span,
)),
2019-06-16 08:43:40 +02:00
})
.to_output_stream())
2019-06-16 08:43:40 +02:00
}