nushell/src/commands/lines.rs

70 lines
1.9 KiB
Rust
Raw Normal View History

use crate::commands::WholeStreamCommand;
use crate::data::{Primitive, Value};
2019-09-11 16:36:50 +02:00
use crate::errors::ShellError;
2019-06-18 02:39:57 +02:00
use crate::prelude::*;
2019-06-22 05:43:37 +02:00
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)
}
}
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();
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
2019-07-08 18:44:53 +02:00
.map(move |v| match v.item {
2019-06-18 02:39:57 +02:00
Value::Primitive(Primitive::String(s)) => {
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(
2019-08-01 03:58:42 +02:00
Value::Primitive(Primitive::String(s.into())).tagged_unknown(),
2019-07-08 18:44:53 +02:00
));
2019-06-18 02:39:57 +02:00
}
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(),
)));
2019-06-18 02:39:57 +02:00
result
}
})
.flatten();
Ok(stream.to_output_stream())
2019-06-18 02:39:57 +02:00
}