nushell/src/commands/lines.rs

72 lines
2.0 KiB
Rust
Raw Normal View History

use crate::commands::WholeStreamCommand;
2019-06-18 02:39:57 +02:00
use crate::prelude::*;
2019-06-22 05:43:37 +02:00
use log::trace;
use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, UntaggedValue};
2019-06-22 05:43:37 +02:00
pub struct Lines;
impl WholeStreamCommand for Lines {
fn name(&self) -> &str {
"lines"
}
fn signature(&self) -> Signature {
Signature::build("lines")
}
fn usage(&self) -> &str {
"Split single string into rows, one per line."
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
lines(args, registry)
}
}
2019-06-22 05:43:37 +02:00
// TODO: "Amount remaining" wrapper
2019-06-18 02:39:57 +02:00
fn lines(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
2019-07-24 00:22:11 +02:00
let args = args.evaluate_once(registry)?;
let tag = args.name_tag();
let name_span = tag.span;
2019-06-18 02:39:57 +02:00
let input = args.input;
2019-07-24 00:22:11 +02:00
2019-06-18 02:39:57 +02:00
let stream = input
.values
.map(move |v| {
if let Ok(s) = v.as_string() {
2019-06-24 04:00:53 +02:00
let split_result: Vec<_> = s.lines().filter(|s| s.trim() != "").collect();
2019-06-22 05:43:37 +02:00
trace!("split result = {:?}", split_result);
2019-06-18 02:39:57 +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(
UntaggedValue::Primitive(Primitive::Line(s.into())).into_untagged_value(),
2019-07-08 18:44:53 +02:00
));
2019-06-18 02:39:57 +02:00
}
result
} else {
2019-06-18 02:39:57 +02:00
let mut result = VecDeque::new();
let value_span = v.tag.span;
result.push_back(Err(ShellError::labeled_error_with_secondary(
"Expected a string from pipeline",
"requires string input",
name_span,
"value originates from here",
value_span,
)));
2019-06-18 02:39:57 +02:00
result
}
})
.flatten();
Ok(stream.to_output_stream())
2019-06-18 02:39:57 +02:00
}