nushell/crates/nu-command/src/commands/roll/command.rs
Fernando Herrera f075e2459d
Commands to engine (#3448)
* commands to engine

* Correction of error in parser

* Added detailed regex error to parse

* better regex error parsing

* clippy corrections

* parse example with test

* secondary error for regex

* removed clone in error parser

* Secondary error message
2021-05-22 10:52:04 -05:00

50 lines
1.2 KiB
Rust

use crate::prelude::*;
use nu_engine::WholeStreamCommand;
use nu_errors::ShellError;
use nu_protocol::{Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::Tagged;
use super::support::{rotate, Direction};
pub struct Command;
pub struct Arguments {
by: Option<Tagged<u64>>,
}
impl WholeStreamCommand for Command {
fn name(&self) -> &str {
"roll"
}
fn signature(&self) -> Signature {
Signature::build("roll").optional("by", SyntaxShape::Int, "the number of times to roll")
}
fn usage(&self) -> &str {
"Rolls the table rows."
}
fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
roll(args)
}
}
pub fn roll(args: CommandArgs) -> Result<OutputStream, ShellError> {
let name = args.call_info.name_tag.clone();
let mut args = args.evaluate_once()?;
let options = Arguments { by: args.opt(0)? };
let values = args.input.drain_vec();
Ok(roll_down(values, &options)
.unwrap_or_else(|| vec![UntaggedValue::nothing().into_value(&name)])
.into_iter()
.to_output_stream())
}
fn roll_down(values: Vec<Value>, Arguments { by: ref n }: &Arguments) -> Option<Vec<Value>> {
rotate(values, n, Direction::Down)
}