From d2a1564b94d78ce4fe977f8f43ce9d87093d4491 Mon Sep 17 00:00:00 2001 From: Jae-Heon Ji <32578710+jaeheonji@users.noreply.github.com> Date: Thu, 2 Dec 2021 03:58:10 +0900 Subject: [PATCH] feat(random): add random-chars (#390) --- crates/nu-command/src/random/chars.rs | 89 +++++++++++++++++++++++++++ crates/nu-command/src/random/mod.rs | 2 + 2 files changed, 91 insertions(+) create mode 100644 crates/nu-command/src/random/chars.rs diff --git a/crates/nu-command/src/random/chars.rs b/crates/nu-command/src/random/chars.rs new file mode 100644 index 0000000000..71021bc63f --- /dev/null +++ b/crates/nu-command/src/random/chars.rs @@ -0,0 +1,89 @@ +use nu_engine::CallExt; +use nu_protocol::ast::Call; +use nu_protocol::engine::{Command, EngineState, Stack}; +use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Value}; +use rand::{ + distributions::{Alphanumeric, Distribution}, + thread_rng, +}; + +const DEFAULT_CHARS_LENGTH: usize = 25; + +#[derive(Clone)] +pub struct SubCommand; + +impl Command for SubCommand { + fn name(&self) -> &str { + "random chars" + } + + fn signature(&self) -> Signature { + Signature::build("random chars") + .named("length", SyntaxShape::Int, "Number of chars", Some('l')) + .category(Category::Random) + } + + fn usage(&self) -> &str { + "Generate random chars" + } + + fn run( + &self, + engine_state: &EngineState, + stack: &mut Stack, + call: &Call, + _input: PipelineData, + ) -> Result { + chars(engine_state, stack, call) + } + + fn examples(&self) -> Vec { + vec![ + Example { + description: "Generate random chars", + example: "random chars", + result: None, + }, + Example { + description: "Generate random chars with specified length", + example: "random chars -l 20", + result: None, + }, + ] + } +} + +fn chars( + engine_state: &EngineState, + stack: &mut Stack, + call: &Call, +) -> Result { + let span = call.head; + let length: Option = call.get_flag(engine_state, stack, "length")?; + + let chars_length = length.unwrap_or(DEFAULT_CHARS_LENGTH); + let mut rng = thread_rng(); + + let random_string = Alphanumeric + .sample_iter(&mut rng) + .take(chars_length) + .map(char::from) + .collect::(); + + Ok(PipelineData::Value(Value::String { + val: random_string, + span, + })) +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_examples() { + use crate::test_examples; + + test_examples(SubCommand {}) + } +} diff --git a/crates/nu-command/src/random/mod.rs b/crates/nu-command/src/random/mod.rs index 1e3cdf0acb..9d429742c2 100644 --- a/crates/nu-command/src/random/mod.rs +++ b/crates/nu-command/src/random/mod.rs @@ -1,5 +1,7 @@ mod bool; +mod chars; mod command; pub use self::bool::SubCommand as Bool; +pub use self::chars::SubCommand as Chars; pub use command::RandomCommand as Random;