nushell/crates/nu-command/src/random/float.rs

118 lines
3.3 KiB
Rust
Raw Normal View History

use nu_engine::command_prelude::*;
use nu_protocol::{FloatRange, Range};
use rand::prelude::{thread_rng, Rng};
use std::ops::Bound;
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"random float"
}
fn signature(&self) -> Signature {
Signature::build("random float")
.input_output_types(vec![(Type::Nothing, Type::Float)])
.allow_variants_without_examples(true)
.optional("range", SyntaxShape::Range, "Range of values.")
.category(Category::Random)
}
fn usage(&self) -> &str {
"Generate a random float within a range [min..max]."
}
fn search_terms(&self) -> Vec<&str> {
vec!["generate"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
float(engine_state, stack, call)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Generate a default float value between 0 and 1",
example: "random float",
result: None,
},
Example {
description: "Generate a random float less than or equal to 500",
example: "random float ..500",
result: None,
},
Example {
description: "Generate a random float greater than or equal to 100000",
example: "random float 100000..",
result: None,
},
Example {
description: "Generate a random float between 1.0 and 1.1",
example: "random float 1.0..1.1",
result: None,
},
]
}
}
fn float(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
) -> Result<PipelineData, ShellError> {
let span = call.head;
Fix span of invalid range (#11207) <!-- if this PR closes one or more issues, you can automatically link the PR with them by using one of the [*linking keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword), e.g. - this PR should close #xxxx - fixes #xxxx you can also mention related issues, PRs or discussions! --> # Description <!-- Thank you for improving Nushell. Please, check our [contributing guide](../CONTRIBUTING.md) and talk to the core team before making major changes. Description of your pull request goes here. **Provide examples and/or screenshots** if your changes affect the user experience. --> Try to improve the error message of invalid range. * before ![Screenshot from 2023-12-02 08-45-23](https://github.com/nushell/nushell/assets/15247421/4d4e3533-b6c6-42c4-9f59-d4d30e4ad5c2) * after ![Screenshot from 2023-12-02 13-18-34](https://github.com/nushell/nushell/assets/15247421/d380dced-4b60-4b1a-9992-9e0727e22054) # User-Facing Changes <!-- List of all changes that impact the user experience here. This helps us keep track of breaking changes. --> # Tests + Formatting <!-- Don't forget to add tests that cover your changes. Make sure you've run and fixed any issues with these commands: - `cargo fmt --all -- --check` to check standard code formatting (`cargo fmt --all` applies these changes) - `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to check that you're using the standard code style - `cargo test --workspace` to check that all tests pass (on Windows make sure to [enable developer mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging)) - `cargo run -- -c "use std testing; testing run-tests --path crates/nu-std"` to run the tests for the standard library > **Note** > from `nushell` you can also use the `toolkit` as follows > ```bash > use toolkit.nu # or use an `env_change` hook to activate it automatically > toolkit check pr > ``` --> # After Submitting <!-- If your PR had any user-facing changes, update [the documentation](https://github.com/nushell/nushell.github.io) after the PR is merged, if necessary. This will help us keep the docs up to date. -->
2023-12-02 13:33:05 +00:00
let range: Option<Spanned<Range>> = call.opt(engine_state, stack, 0)?;
let mut thread_rng = thread_rng();
match range {
Some(range) => {
let range_span = range.span;
let range = FloatRange::from(range.item);
if range.step() < 0.0 {
return Err(ShellError::InvalidRange {
left_flank: range.start().to_string(),
right_flank: match range.end() {
Bound::Included(end) | Bound::Excluded(end) => end.to_string(),
Bound::Unbounded => "".into(),
},
span: range_span,
});
}
let value = match range.end() {
Bound::Included(end) => thread_rng.gen_range(range.start()..=end),
Bound::Excluded(end) => thread_rng.gen_range(range.start()..end),
Bound::Unbounded => thread_rng.gen_range(range.start()..f64::INFINITY),
};
Ok(PipelineData::Value(Value::float(value, span), None))
}
None => Ok(PipelineData::Value(
Value::float(thread_rng.gen_range(0.0..1.0), span),
None,
)),
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}