2020-06-27 07:38:19 +02:00
|
|
|
use crate::commands::WholeStreamCommand;
|
|
|
|
use crate::prelude::*;
|
|
|
|
use nu_errors::ShellError;
|
2020-08-02 09:29:29 +02:00
|
|
|
use nu_protocol::{ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
|
|
|
|
use nu_source::Tagged;
|
2020-06-27 07:38:19 +02:00
|
|
|
|
|
|
|
pub struct SubCommand;
|
|
|
|
|
2020-08-02 09:29:29 +02:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
pub struct SubCommandArgs {
|
|
|
|
separator: Option<Tagged<String>>,
|
|
|
|
}
|
|
|
|
|
2020-06-27 07:38:19 +02:00
|
|
|
#[async_trait]
|
|
|
|
impl WholeStreamCommand for SubCommand {
|
|
|
|
fn name(&self) -> &str {
|
|
|
|
"str collect"
|
|
|
|
}
|
|
|
|
|
|
|
|
fn signature(&self) -> Signature {
|
2020-08-02 09:29:29 +02:00
|
|
|
Signature::build("str collect").desc(self.usage()).optional(
|
|
|
|
"separator",
|
|
|
|
SyntaxShape::String,
|
|
|
|
"the separator to put between the different values",
|
|
|
|
)
|
2020-06-27 07:38:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
fn usage(&self) -> &str {
|
|
|
|
"collects a list of strings into a string"
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn run(
|
|
|
|
&self,
|
|
|
|
args: CommandArgs,
|
2020-08-02 09:29:29 +02:00
|
|
|
registry: &CommandRegistry,
|
2020-06-27 07:38:19 +02:00
|
|
|
) -> Result<OutputStream, ShellError> {
|
2020-08-02 09:29:29 +02:00
|
|
|
collect(args, registry).await
|
2020-06-27 07:38:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
fn examples(&self) -> Vec<Example> {
|
|
|
|
vec![Example {
|
|
|
|
description: "Collect a list of string",
|
|
|
|
example: "echo ['a' 'b' 'c'] | str collect",
|
|
|
|
result: Some(vec![Value::from("abc")]),
|
|
|
|
}]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-02 09:29:29 +02:00
|
|
|
pub async fn collect(
|
|
|
|
args: CommandArgs,
|
|
|
|
registry: &CommandRegistry,
|
|
|
|
) -> Result<OutputStream, ShellError> {
|
|
|
|
let tag = args.call_info.name_tag.clone();
|
|
|
|
let (SubCommandArgs { separator }, input) = args.process(registry).await?;
|
|
|
|
let separator = separator.map(|tagged| tagged.item).unwrap_or_default();
|
|
|
|
|
|
|
|
let strings: Vec<Result<String, ShellError>> =
|
|
|
|
input.map(|value| value.as_string()).collect().await;
|
|
|
|
let strings: Vec<String> = strings.into_iter().collect::<Result<_, _>>()?;
|
|
|
|
let output = strings.join(&separator);
|
|
|
|
|
|
|
|
Ok(OutputStream::one(ReturnSuccess::value(
|
|
|
|
UntaggedValue::string(output).into_value(tag),
|
|
|
|
)))
|
|
|
|
}
|
|
|
|
|
2020-06-27 07:38:19 +02:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::SubCommand;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn examples_work_as_expected() {
|
|
|
|
use crate::examples::test as test_examples;
|
|
|
|
|
|
|
|
test_examples(SubCommand {})
|
|
|
|
}
|
|
|
|
}
|