nushell/src/commands/get.rs

78 lines
2.0 KiB
Rust
Raw Normal View History

2019-05-29 06:02:36 +02:00
use crate::errors::ShellError;
use crate::object::Value;
use crate::prelude::*;
fn get_member(path: &str, obj: &Value) -> Option<Value> {
let mut current = obj;
for p in path.split(".") {
match current.get_data_by_key(p) {
Some(v) => current = v,
None => {
return Some(Value::Error(Box::new(ShellError::string(format!(
"Object field name not found: {}",
p
)))))
}
}
}
Some(current.copy())
}
2019-06-05 03:53:38 +02:00
pub fn get(args: CommandArgs) -> Result<OutputStream, ShellError> {
2019-06-22 03:36:57 +02:00
if args.len() == 0 {
2019-06-08 00:35:07 +02:00
if let Some(span) = args.name_span {
return Err(ShellError::labeled_error(
"Get requires a field or field path",
"needs parameter",
span,
));
} else {
return Err(ShellError::string("get requires fields."));
}
2019-05-29 06:02:36 +02:00
}
2019-06-22 03:36:57 +02:00
let amount = args.expect_nth(0)?.as_i64();
2019-06-11 08:26:03 +02:00
// If it's a number, get the row instead of the column
if let Ok(amount) = amount {
return Ok(args
.input
.skip(amount as u64)
.take(1)
.map(|v| ReturnValue::Value(v))
.boxed());
}
2019-06-22 03:36:57 +02:00
let fields: Result<Vec<String>, _> = args
.args
.positional
.unwrap()
.iter()
.map(|a| a.as_string())
.collect();
2019-05-29 06:02:36 +02:00
let fields = fields?;
let stream = args
.input
.map(move |item| {
let mut result = VecDeque::new();
for field in &fields {
match get_member(field, &item) {
2019-05-29 06:02:36 +02:00
Some(Value::List(l)) => {
for item in l {
result.push_back(ReturnValue::Value(item.copy()));
}
}
Some(x) => result.push_back(ReturnValue::Value(x.copy())),
None => {}
}
}
result
})
.flatten();
Ok(stream.boxed())
}