nushell/src/commands/get.rs

75 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;
2019-06-22 05:43:37 +02:00
use crate::parser::Span;
2019-05-29 06:02:36 +02:00
use crate::prelude::*;
fn get_member(path: &str, span: Span, obj: &Value) -> Result<Value, ShellError> {
let mut current = obj;
for p in path.split(".") {
match current.get_data_by_key(p) {
Some(v) => current = v,
None => {
return Err(ShellError::labeled_error(
2019-06-15 19:52:55 +02:00
"Unknown field",
2019-06-15 20:36:17 +02:00
"object missing field",
2019-06-15 19:52:55 +02:00
span,
));
}
}
}
Ok(current.copy())
}
2019-06-05 03:53:38 +02:00
pub fn get(args: CommandArgs) -> Result<OutputStream, ShellError> {
2019-06-22 05:43:37 +02:00
if args.len() == 0 {
2019-06-15 20:36:17 +02:00
return Err(ShellError::maybe_labeled_error(
"Get requires a field or field path",
"needs parameter",
args.name_span,
));
2019-05-29 06:02:36 +02:00
}
2019-06-22 05:43:37 +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
.values
2019-06-11 08:26:03 +02:00
.skip(amount as u64)
.take(1)
.from_input_stream());
2019-06-11 08:26:03 +02:00
}
2019-06-15 19:52:55 +02:00
let fields: Result<Vec<(String, Span)>, _> = args
2019-06-22 05:43:37 +02:00
.positional_iter()
2019-06-15 19:52:55 +02:00
.map(|a| (a.as_string().map(|x| (x, a.span))))
.collect();
2019-06-22 22:46:16 +02:00
2019-05-29 06:02:36 +02:00
let fields = fields?;
let stream = args
.input
.values
2019-05-29 06:02:36 +02:00
.map(move |item| {
let mut result = VecDeque::new();
for field in &fields {
2019-06-15 19:52:55 +02:00
match get_member(&field.0, field.1, &item) {
Ok(Value::List(l)) => {
2019-05-29 06:02:36 +02:00
for item in l {
result.push_back(ReturnSuccess::value(item.copy()));
2019-05-29 06:02:36 +02:00
}
}
Ok(x) => result.push_back(ReturnSuccess::value(x.copy())),
Err(_) => {}
2019-05-29 06:02:36 +02:00
}
}
result
})
.flatten();
Ok(stream.to_output_stream())
2019-05-29 06:02:36 +02:00
}