support filesize arguments in random binary/chars (#14068)

Closes #13920

# User-Facing Changes

`random binary` and `random chars` now support filesize arguments:

```nushell
random binary 1kb
random chars --length 1kb
```
This commit is contained in:
Solomon 2024-10-12 06:49:05 +00:00 committed by GitHub
parent e32e55938b
commit d83781ddec
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 55 additions and 7 deletions

View file

@ -14,7 +14,11 @@ impl Command for SubCommand {
Signature::build("random binary") Signature::build("random binary")
.input_output_types(vec![(Type::Nothing, Type::Binary)]) .input_output_types(vec![(Type::Nothing, Type::Binary)])
.allow_variants_without_examples(true) .allow_variants_without_examples(true)
.required("length", SyntaxShape::Int, "Length of the output binary.") .required(
"length",
SyntaxShape::OneOf(vec![SyntaxShape::Int, SyntaxShape::Filesize]),
"Length of the output binary.",
)
.category(Category::Random) .category(Category::Random)
} }
@ -43,11 +47,18 @@ impl Command for SubCommand {
} }
fn examples(&self) -> Vec<Example> { fn examples(&self) -> Vec<Example> {
vec![Example { vec![
description: "Generate 16 random bytes", Example {
example: "random binary 16", description: "Generate 16 random bytes",
result: None, example: "random binary 16",
}] result: None,
},
Example {
description: "Generate 1 random kilobyte",
example: "random binary 1kb",
result: None,
},
]
} }
} }

View file

@ -21,7 +21,7 @@ impl Command for SubCommand {
.allow_variants_without_examples(true) .allow_variants_without_examples(true)
.named( .named(
"length", "length",
SyntaxShape::Int, SyntaxShape::OneOf(vec![SyntaxShape::Int, SyntaxShape::Filesize]),
"Number of chars (default 25)", "Number of chars (default 25)",
Some('l'), Some('l'),
) )
@ -58,6 +58,11 @@ impl Command for SubCommand {
example: "random chars --length 20", example: "random chars --length 20",
result: None, result: None,
}, },
Example {
description: "Generate one kilobyte of random chars",
example: "random chars --length 1kb",
result: None,
},
] ]
} }
} }

View file

@ -0,0 +1,21 @@
use nu_test_support::nu;
#[test]
fn generates_bytes_of_specified_length() {
let actual = nu!(r#"
random binary 16 | bytes length
"#);
let result = actual.out;
assert_eq!(result, "16");
}
#[test]
fn generates_bytes_of_specified_filesize() {
let actual = nu!(r#"
random binary 1kb | bytes length
"#);
let result = actual.out;
assert_eq!(result, "1000");
}

View file

@ -9,3 +9,13 @@ fn generates_chars_of_specified_length() {
let result = actual.out; let result = actual.out;
assert_eq!(result, "15"); assert_eq!(result, "15");
} }
#[test]
fn generates_chars_of_specified_filesize() {
let actual = nu!(r#"
random chars --length 1kb | str stats | get bytes
"#);
let result = actual.out;
assert_eq!(result, "1000");
}

View file

@ -1,3 +1,4 @@
mod binary;
mod bool; mod bool;
mod chars; mod chars;
mod dice; mod dice;