nushell/src/commands/split_row.rs

54 lines
1.8 KiB
Rust
Raw Normal View History

2019-05-30 07:08:42 +02:00
use crate::errors::ShellError;
use crate::object::{Primitive, Value};
use crate::prelude::*;
use log::trace;
2019-05-30 07:08:42 +02:00
2019-05-31 22:34:15 +02:00
pub fn split_row(args: CommandArgs) -> Result<OutputStream, ShellError> {
2019-08-01 03:58:42 +02:00
let positional: Vec<Tagged<Value>> = args.positional_iter().cloned().collect();
let span = args.call_info.name_span;
2019-06-22 05:43:37 +02:00
if positional.len() == 0 {
return Err(ShellError::labeled_error(
2019-06-18 02:39:09 +02:00
"Split-row needs more information",
"needs parameter (eg split-row \"\\n\")",
args.call_info.name_span,
2019-06-18 02:39:09 +02:00
));
}
2019-05-30 07:08:42 +02:00
let input = args.input;
let stream = input
.values
2019-07-08 18:44:53 +02:00
.map(move |v| match v.item {
2019-08-01 03:58:42 +02:00
Value::Primitive(Primitive::String(ref s)) => {
2019-06-22 05:43:37 +02:00
let splitter = positional[0].as_string().unwrap().replace("\\n", "\n");
trace!("splitting with {:?}", splitter);
2019-05-30 07:08:42 +02:00
let split_result: Vec<_> = s.split(&splitter).filter(|s| s.trim() != "").collect();
trace!("split result = {:?}", split_result);
2019-05-30 07:08:42 +02:00
let mut result = VecDeque::new();
for s in split_result {
2019-07-08 18:44:53 +02:00
result.push_back(ReturnSuccess::value(
Value::Primitive(Primitive::String(s.into())).simple_spanned(v.span()),
2019-07-08 18:44:53 +02:00
));
2019-05-30 07:08:42 +02:00
}
result
}
_ => {
2019-06-16 01:03:49 +02:00
let mut result = VecDeque::new();
result.push_back(Err(ShellError::labeled_error_with_secondary(
"Expected a string from pipeline",
"requires string input",
span,
"value originates from here",
v.span(),
)));
2019-05-30 07:08:42 +02:00
result
}
})
.flatten();
Ok(stream.to_output_stream())
2019-05-30 07:08:42 +02:00
}