nushell/src/commands/lines.rs
Jonathan Turner 193b00764b
Stream support (#812)
* Moves off of draining between filters. Instead, the sink will pull on the stream, and will drain element-wise. This moves the whole stream to being lazy.
* Adds ctrl-c support and connects it into some of the key points where we pull on the stream. If a ctrl-c is detect, we immediately halt pulling on the stream and return to the prompt.
* Moves away from having a SourceMap where anchor locations are stored. Now AnchorLocation is kept directly in the Tag.
* To make this possible, split tag and span. Span is largely used in the parser and is copyable. Tag is now no longer copyable.
2019-10-13 17:12:43 +13:00

72 lines
2.0 KiB
Rust

use crate::commands::WholeStreamCommand;
use crate::data::{Primitive, Value};
use crate::errors::ShellError;
use crate::prelude::*;
use log::trace;
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)
}
}
// TODO: "Amount remaining" wrapper
fn lines(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let args = args.evaluate_once(registry)?;
let tag = args.name_tag();
let input = args.input;
let input: InputStream = trace_stream!(target: "nu::trace_stream::lines", "input" = input);
let stream = input
.values
.map(move |v| match v.item {
Value::Primitive(Primitive::String(s)) => {
let split_result: Vec<_> = s.lines().filter(|s| s.trim() != "").collect();
trace!("split result = {:?}", split_result);
let mut result = VecDeque::new();
for s in split_result {
result.push_back(ReturnSuccess::value(
Value::Primitive(Primitive::String(s.into())).tagged_unknown(),
));
}
result
}
_ => {
let mut result = VecDeque::new();
result.push_back(Err(ShellError::labeled_error_with_secondary(
"Expected a string from pipeline",
"requires string input",
&tag,
"value originates from here",
v.tag(),
)));
result
}
})
.flatten();
Ok(stream.to_output_stream())
}