1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use crate::prelude::*;
use nu_engine::WholeStreamCommand;
use nu_errors::ShellError;
use nu_protocol::{Signature, SyntaxShape, UntaggedValue};
use nu_source::Tagged;
use rand::distributions::{Alphanumeric, Distribution};
use rand::thread_rng;
pub struct SubCommand;
pub struct CharsArgs {
length: Option<Tagged<u32>>,
}
const DEFAULT_CHARS_LENGTH: u32 = 25;
impl WholeStreamCommand 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'),
)
}
fn usage(&self) -> &str {
"Generate random chars"
}
fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
chars(args)
}
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,
},
]
}
}
pub fn chars(args: CommandArgs) -> Result<OutputStream, ShellError> {
let cmd_args = CharsArgs {
length: args.get_flag("length")?,
};
let chars_length = cmd_args.length.map_or(DEFAULT_CHARS_LENGTH, |l| l.item);
let mut rng = thread_rng();
let random_string: String = Alphanumeric
.sample_iter(&mut rng)
.take(chars_length as usize)
.map(char::from)
.collect();
Ok(OutputStream::one(UntaggedValue::string(random_string)))
}
#[cfg(test)]
mod tests {
use super::ShellError;
use super::SubCommand;
#[test]
fn examples_work_as_expected() -> Result<(), ShellError> {
use crate::examples::test as test_examples;
test_examples(SubCommand {})
}
}