nushell/src/commands/from_ini.rs

62 lines
1.9 KiB
Rust
Raw Normal View History

use crate::object::{Primitive, SpannedDictBuilder, Value};
2019-06-16 08:43:40 +02:00
use crate::prelude::*;
use std::collections::HashMap;
2019-07-09 06:31:26 +02:00
fn convert_ini_second_to_nu_value(
v: &HashMap<String, String>,
span: impl Into<Span>,
) -> Spanned<Value> {
let mut second = SpannedDictBuilder::new(span);
2019-06-16 08:43:40 +02:00
for (key, value) in v.into_iter() {
2019-07-09 06:31:26 +02:00
second.insert(key.clone(), Primitive::String(value.clone()));
2019-06-16 08:43:40 +02:00
}
2019-07-09 06:31:26 +02:00
second.into_spanned_value()
2019-06-16 08:43:40 +02:00
}
2019-07-09 06:31:26 +02:00
fn convert_ini_top_to_nu_value(
v: &HashMap<String, HashMap<String, String>>,
span: impl Into<Span>,
) -> Spanned<Value> {
let span = span.into();
let mut top_level = SpannedDictBuilder::new(span);
2019-06-16 08:43:40 +02:00
for (key, value) in v.iter() {
2019-07-09 06:31:26 +02:00
top_level.insert_spanned(key.clone(), convert_ini_second_to_nu_value(value, span));
2019-06-16 08:43:40 +02:00
}
2019-07-09 06:31:26 +02:00
top_level.into_spanned_value()
2019-06-16 08:43:40 +02:00
}
2019-07-09 06:31:26 +02:00
pub fn from_ini_string_to_value(
s: String,
span: impl Into<Span>,
) -> Result<Spanned<Value>, Box<dyn std::error::Error>> {
2019-06-16 08:43:40 +02:00
let v: HashMap<String, HashMap<String, String>> = serde_ini::from_str(&s)?;
2019-07-09 06:31:26 +02:00
Ok(convert_ini_top_to_nu_value(&v, span))
2019-06-16 08:43:40 +02:00
}
pub fn from_ini(args: CommandArgs) -> Result<OutputStream, ShellError> {
let out = args.input;
let span = args.call_info.name_span;
2019-06-16 08:43:40 +02:00
Ok(out
.values
2019-07-08 18:44:53 +02:00
.map(move |a| match a.item {
2019-07-09 06:31:26 +02:00
Value::Primitive(Primitive::String(s)) => match from_ini_string_to_value(s, span) {
2019-07-08 18:44:53 +02:00
Ok(x) => ReturnSuccess::value(x.spanned(a.span)),
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
}