nushell/crates/nu-cli/src/commands/split/row.rs

97 lines
2.7 KiB
Rust
Raw Normal View History

use crate::commands::WholeStreamCommand;
2019-05-30 07:08:42 +02:00
use crate::prelude::*;
use log::trace;
use nu_errors::ShellError;
2019-11-30 01:21:05 +01:00
use nu_protocol::{Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue};
use nu_source::Tagged;
2019-05-30 07:08:42 +02:00
#[derive(Deserialize)]
struct SplitRowArgs {
2019-08-20 08:11:11 +02:00
separator: Tagged<String>,
}
2020-05-24 08:41:30 +02:00
pub struct SubCommand;
2020-05-29 10:22:52 +02:00
#[async_trait]
2020-05-24 08:41:30 +02:00
impl WholeStreamCommand for SubCommand {
fn name(&self) -> &str {
2020-05-24 08:41:30 +02:00
"split row"
}
fn signature(&self) -> Signature {
2020-05-24 08:41:30 +02:00
Signature::build("split row").required(
2019-10-28 06:15:35 +01:00
"separator",
SyntaxShape::Any,
"the character that denotes what separates rows",
)
}
fn usage(&self) -> &str {
2020-05-24 08:41:30 +02:00
"splits contents over multiple rows via the separator."
}
2020-05-29 10:22:52 +02:00
async fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
split_row(args, registry).await
}
}
async fn split_row(
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let name = args.call_info.name_tag.clone();
let (SplitRowArgs { separator }, input) = args.process(&registry).await?;
Ok(input
.flat_map(move |v| {
if let Ok(s) = v.as_string() {
2019-08-20 08:11:11 +02:00
let splitter = separator.item.replace("\\n", "\n");
trace!("splitting with {:?}", splitter);
let split_result: Vec<String> = s
.split(&splitter)
.filter_map(|s| {
if s.trim() != "" {
Some(s.to_string())
} else {
None
}
})
.collect();
2019-05-30 07:08:42 +02:00
trace!("split result = {:?}", split_result);
2019-05-30 07:08:42 +02:00
futures::stream::iter(split_result.into_iter().map(move |s| {
ReturnSuccess::value(
UntaggedValue::Primitive(Primitive::String(s)).into_value(&v.tag),
)
}))
.to_output_stream()
} else {
OutputStream::one(Err(ShellError::labeled_error_with_secondary(
"Expected a string from pipeline",
"requires string input",
name.span,
"value originates from here",
v.tag.span,
)))
2019-05-30 07:08:42 +02:00
}
})
.to_output_stream())
2019-05-30 07:08:42 +02:00
}
#[cfg(test)]
mod tests {
2020-05-24 08:41:30 +02:00
use super::SubCommand;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
2020-05-24 08:41:30 +02:00
test_examples(SubCommand {})
}
}