nushell/crates/nu-cli/src/commands/trim.rs

96 lines
2.3 KiB
Rust
Raw Normal View History

use crate::commands::WholeStreamCommand;
2019-06-01 05:43:59 +02:00
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::{Dictionary, Primitive, ReturnSuccess, Signature, UntaggedValue, Value};
2019-06-01 05:43:59 +02:00
pub struct Trim;
2020-05-29 10:22:52 +02:00
#[async_trait]
impl WholeStreamCommand for Trim {
fn name(&self) -> &str {
"trim"
}
fn signature(&self) -> Signature {
Signature::build("trim")
}
fn usage(&self) -> &str {
"Trim leading and following whitespace from text data."
}
2020-05-29 10:22:52 +02:00
async fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
trim(args, registry)
}
2020-05-18 17:40:44 +02:00
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Trims surrounding whitespace and outputs \"Hello world\"",
example: "echo \" Hello world\" | trim",
2020-05-18 17:40:44 +02:00
result: Some(vec![Value::from("Hello world")]),
}]
}
}
fn trim_primitive(p: &mut Primitive) {
match p {
Primitive::String(s) | Primitive::Line(s) => *p = Primitive::String(s.trim().to_string()),
Primitive::Nothing
| Primitive::Int(_)
| Primitive::Decimal(_)
2020-07-11 04:17:37 +02:00
| Primitive::Filesize(_)
| Primitive::ColumnPath(_)
| Primitive::Pattern(_)
| Primitive::Boolean(_)
| Primitive::Date(_)
| Primitive::Duration(_)
| Primitive::Range(_)
| Primitive::Path(_)
| Primitive::Binary(_)
| Primitive::BeginningOfStream
| Primitive::EndOfStream => (),
}
}
fn trim_row(d: &mut Dictionary) {
for (_, mut value) in d.entries.iter_mut() {
trim_value(&mut value);
}
}
fn trim_value(v: &mut Value) {
match &mut v.value {
UntaggedValue::Primitive(p) => trim_primitive(p),
UntaggedValue::Row(row) => trim_row(row),
_ => (),
};
}
fn trim(args: CommandArgs, _registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
Ok(args
.input
.map(|v| {
let mut trimmed = v;
trim_value(&mut trimmed);
ReturnSuccess::value(trimmed)
2019-07-09 06:31:26 +02:00
})
.to_output_stream())
2019-06-01 05:43:59 +02:00
}
#[cfg(test)]
mod tests {
use super::Trim;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(Trim {})
}
}