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

174 lines
5.1 KiB
Rust
Raw Normal View History

use crate::commands::WholeStreamCommand;
2019-09-08 01:43:53 +02:00
use crate::prelude::*;
use nu_errors::ShellError;
2020-05-27 20:07:53 +02:00
use nu_protocol::hir::Operator;
use nu_protocol::{
Primitive, Range, RangeInclusion, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value,
2020-05-27 20:07:53 +02:00
};
2019-09-08 01:43:53 +02:00
pub struct Echo;
#[derive(Deserialize)]
pub struct EchoArgs {
pub rest: Vec<Value>,
}
2020-05-29 10:22:52 +02:00
#[async_trait]
impl WholeStreamCommand for Echo {
2019-09-08 01:43:53 +02:00
fn name(&self) -> &str {
"echo"
}
fn signature(&self) -> Signature {
2019-10-28 06:15:35 +01:00
Signature::build("echo").rest(SyntaxShape::Any, "the values to echo")
2019-09-08 01:43:53 +02:00
}
fn usage(&self) -> &str {
2019-09-25 00:15:53 +02:00
"Echo the arguments back to the user."
2019-09-08 01:43:53 +02:00
}
2020-05-29 10:22:52 +02:00
async fn run(
2019-09-08 01:43:53 +02:00
&self,
args: CommandArgs,
2019-09-08 01:43:53 +02:00
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
echo(args, registry).await
2019-09-08 01:43:53 +02:00
}
2020-05-12 07:17:17 +02:00
fn examples(&self) -> Vec<Example> {
vec![
2020-05-12 07:17:17 +02:00
Example {
description: "Put a hello message in the pipeline",
example: "echo 'hello'",
result: Some(vec![Value::from("hello")]),
2020-05-12 07:17:17 +02:00
},
Example {
description: "Print the value of the special '$nu' variable",
example: "echo $nu",
result: None,
2020-05-12 07:17:17 +02:00
},
]
}
2019-09-08 01:43:53 +02:00
}
async fn echo(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let (args, _): (EchoArgs, _) = args.process(&registry).await?;
2019-09-08 01:43:53 +02:00
let stream = args.rest.into_iter().map(|i| match i.as_string() {
Ok(s) => OutputStream::one(Ok(ReturnSuccess::Value(
UntaggedValue::string(s).into_value(i.tag.clone()),
))),
_ => match i {
Value {
value: UntaggedValue::Table(table),
..
} => futures::stream::iter(table.into_iter().map(ReturnSuccess::value))
.to_output_stream(),
Value {
value: UntaggedValue::Primitive(Primitive::Range(range)),
tag,
} => futures::stream::iter(RangeIterator::new(*range, tag)).to_output_stream(),
_ => OutputStream::one(Ok(ReturnSuccess::Value(i.clone()))),
},
});
Ok(futures::stream::iter(stream).flatten().to_output_stream())
}
struct RangeIterator {
curr: Primitive,
end: Primitive,
tag: Tag,
is_end_inclusive: bool,
}
impl RangeIterator {
pub fn new(range: Range, tag: Tag) -> RangeIterator {
let start = match range.from.0.item {
Primitive::Nothing => Primitive::Int(0.into()),
x => x,
};
RangeIterator {
curr: start,
end: range.to.0.item,
tag,
is_end_inclusive: matches!(range.to.1, RangeInclusion::Inclusive),
2019-09-08 01:43:53 +02:00
}
}
}
2019-09-08 01:43:53 +02:00
impl Iterator for RangeIterator {
type Item = Result<ReturnSuccess, ShellError>;
fn next(&mut self) -> Option<Self::Item> {
let ordering = if self.end == Primitive::Nothing {
Ordering::Less
} else {
let result =
nu_data::base::coerce_compare_primitive(&self.curr, &self.end).map_err(|_| {
ShellError::labeled_error(
"Cannot create range",
"unsupported range",
self.tag.span,
)
});
if let Err(result) = result {
return Some(Err(result));
}
let result = result
.expect("Internal error: the error case was already protected, but that failed");
result.compare()
};
use std::cmp::Ordering;
if (ordering == Ordering::Less) || (self.is_end_inclusive && ordering == Ordering::Equal) {
let output = UntaggedValue::Primitive(self.curr.clone()).into_value(self.tag.clone());
let next_value = nu_data::value::compute_values(
Operator::Plus,
&UntaggedValue::Primitive(self.curr.clone()),
&UntaggedValue::int(1),
);
self.curr = match next_value {
Ok(result) => match result {
UntaggedValue::Primitive(p) => p,
_ => {
return Some(Err(ShellError::unimplemented(
"Internal error: expected a primitive result from increment",
)));
}
},
Err((left_type, right_type)) => {
return Some(Err(ShellError::coerce_error(
left_type.spanned(self.tag.span),
right_type.spanned(self.tag.span),
)));
}
};
Some(ReturnSuccess::value(output))
} else {
// TODO: add inclusive/exclusive ranges
None
}
}
2019-09-08 01:43:53 +02:00
}
#[cfg(test)]
mod tests {
use super::Echo;
use super::ShellError;
#[test]
fn examples_work_as_expected() -> Result<(), ShellError> {
use crate::examples::test as test_examples;
Ok(test_examples(Echo {})?)
}
}