nushell/src/commands/split_row.rs

53 lines
1.7 KiB
Rust
Raw Normal View History

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