nushell/src/commands/split_row.rs

74 lines
2.1 KiB
Rust
Raw Normal View History

use crate::commands::WholeStreamCommand;
use crate::data::{Primitive, Value};
2019-09-11 14:36:50 +00:00
use crate::errors::ShellError;
2019-05-30 05:08:42 +00:00
use crate::prelude::*;
use log::trace;
2019-05-30 05:08:42 +00:00
#[derive(Deserialize)]
struct SplitRowArgs {
2019-08-20 06:11:11 +00:00
separator: Tagged<String>,
}
pub struct SplitRow;
impl WholeStreamCommand for SplitRow {
fn name(&self) -> &str {
"split-row"
}
fn signature(&self) -> Signature {
Signature::build("split-row").required("separator", SyntaxShape::Any)
}
fn usage(&self) -> &str {
"Split row contents over multiple rows via the separator."
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
args.process(registry, split_row)?.run()
}
}
fn split_row(
2019-08-20 06:11:11 +00:00
SplitRowArgs { separator }: SplitRowArgs,
RunnableContext { input, name, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> {
2019-05-30 05:08:42 +00:00
let stream = input
.values
2019-07-08 16:44:53 +00:00
.map(move |v| match v.item {
2019-08-01 01:58:42 +00:00
Value::Primitive(Primitive::String(ref s)) => {
2019-08-20 06:11:11 +00:00
let splitter = separator.item.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(
2019-08-06 03:03:13 +00:00
Value::Primitive(Primitive::String(s.into())).tagged(v.tag()),
2019-07-08 16:44:53 +00:00
));
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::labeled_error_with_secondary(
"Expected a string from pipeline",
"requires string input",
name,
"value originates from here",
v.tag(),
)));
2019-05-30 05:08:42 +00:00
result
}
})
.flatten();
Ok(stream.to_output_stream())
2019-05-30 05:08:42 +00:00
}