mirror of
https://github.com/nushell/nushell
synced 2024-12-26 13:03:07 +00:00
feat(random): add random-chars (#390)
This commit is contained in:
parent
7cf96c6597
commit
d2a1564b94
2 changed files with 91 additions and 0 deletions
89
crates/nu-command/src/random/chars.rs
Normal file
89
crates/nu-command/src/random/chars.rs
Normal file
|
@ -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<nu_protocol::PipelineData, nu_protocol::ShellError> {
|
||||
chars(engine_state, stack, call)
|
||||
}
|
||||
|
||||
fn examples(&self) -> Vec<Example> {
|
||||
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<PipelineData, ShellError> {
|
||||
let span = call.head;
|
||||
let length: Option<usize> = 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::<String>();
|
||||
|
||||
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 {})
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
|
|
Loading…
Reference in a new issue