nushell/src/commands/split_row.rs

53 lines
1.7 KiB
Rust
Raw Normal View History

2019-05-30 07:08:42 +02:00
use crate::errors::ShellError;
use crate::object::{Primitive, Value};
2019-06-22 05:43:37 +02:00
use crate::parser::Spanned;
2019-05-30 07:08:42 +02:00
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-06-22 05:43:37 +02:00
let positional: Vec<Spanned<Value>> = args.positional_iter().cloned().collect();
let span = args.name_span;
if positional.len() == 0 {
2019-06-18 02:39:09 +02:00
return Err(ShellError::maybe_labeled_error(
"Split-row needs more information",
"needs parameter (eg split-row \"\\n\")",
args.name_span,
));
}
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-05-30 07:08:42 +02:00
Value::Primitive(Primitive::String(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())).spanned(v.span),
));
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::maybe_labeled_error(
"Expected string values from pipeline",
"expects strings from pipeline",
span,
)));
2019-05-30 07:08:42 +02:00
result
}
})
.flatten();
Ok(stream.to_output_stream())
2019-05-30 07:08:42 +02:00
}