nushell/crates/nu-command/src/strings/build_string.rs

77 lines
2.0 KiB
Rust
Raw Normal View History

2021-09-29 20:25:05 +02:00
use nu_engine::eval_expression;
use nu_protocol::ast::Call;
2021-10-25 18:58:58 +02:00
use nu_protocol::engine::{Command, EngineState, Stack};
2021-10-25 06:01:02 +02:00
use nu_protocol::{
Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, SyntaxShape, Value,
};
2021-09-29 20:25:05 +02:00
2021-10-25 06:01:02 +02:00
#[derive(Clone)]
2021-09-29 20:25:05 +02:00
pub struct BuildString;
impl Command for BuildString {
fn name(&self) -> &str {
"build-string"
}
fn usage(&self) -> &str {
"Create a string from the arguments."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("build-string").rest("rest", SyntaxShape::String, "list of string")
}
2021-10-09 15:10:10 +02:00
fn examples(&self) -> Vec<Example> {
vec![
Example {
example: "build-string a b c",
description: "Builds a string from letters a b c",
result: Some(Value::String {
val: "abc".to_string(),
span: Span::unknown(),
}),
},
Example {
example: "build-string (1 + 2) = one ' ' plus ' ' two",
description: "Builds a string from letters a b c",
result: Some(Value::String {
val: "3=one plus two".to_string(),
span: Span::unknown(),
}),
},
]
}
2021-09-29 20:25:05 +02:00
fn run(
&self,
2021-10-25 08:31:39 +02:00
engine_state: &EngineState,
stack: &mut Stack,
2021-09-29 20:25:05 +02:00
call: &Call,
2021-10-25 06:01:02 +02:00
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
2021-09-29 20:25:05 +02:00
let output = call
.positional
.iter()
2021-10-25 08:31:39 +02:00
.map(|expr| eval_expression(engine_state, stack, expr).map(|val| val.into_string()))
2021-09-29 20:25:05 +02:00
.collect::<Result<Vec<String>, ShellError>>()?;
Ok(Value::String {
val: output.join(""),
span: call.head,
2021-10-25 06:01:02 +02:00
}
.into_pipeline_data())
2021-09-29 20:25:05 +02:00
}
}
2021-10-09 15:10:10 +02:00
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(BuildString {})
}
}