2020-09-19 23:29:51 +02:00
|
|
|
use crate::command_registry::CommandRegistry;
|
2020-03-10 23:00:08 +01:00
|
|
|
use crate::commands::WholeStreamCommand;
|
|
|
|
use crate::prelude::*;
|
|
|
|
use nu_errors::ShellError;
|
2020-06-13 10:43:21 +02:00
|
|
|
use nu_protocol::{ReturnSuccess, Value};
|
2020-03-10 23:00:08 +01:00
|
|
|
|
|
|
|
use rand::seq::SliceRandom;
|
|
|
|
use rand::thread_rng;
|
|
|
|
|
|
|
|
pub struct Shuffle;
|
|
|
|
|
2020-05-29 10:22:52 +02:00
|
|
|
#[async_trait]
|
2020-03-10 23:00:08 +01:00
|
|
|
impl WholeStreamCommand for Shuffle {
|
|
|
|
fn name(&self) -> &str {
|
|
|
|
"shuffle"
|
|
|
|
}
|
|
|
|
|
|
|
|
fn usage(&self) -> &str {
|
|
|
|
"Shuffle rows randomly."
|
|
|
|
}
|
|
|
|
|
2020-05-29 10:22:52 +02:00
|
|
|
async fn run(
|
2020-03-10 23:00:08 +01:00
|
|
|
&self,
|
|
|
|
args: CommandArgs,
|
|
|
|
registry: &CommandRegistry,
|
|
|
|
) -> Result<OutputStream, ShellError> {
|
2020-06-13 10:43:21 +02:00
|
|
|
shuffle(args, registry).await
|
2020-03-10 23:00:08 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-13 10:43:21 +02:00
|
|
|
async fn shuffle(
|
|
|
|
args: CommandArgs,
|
|
|
|
_registry: &CommandRegistry,
|
|
|
|
) -> Result<OutputStream, ShellError> {
|
|
|
|
let input = args.input;
|
|
|
|
let mut values: Vec<Value> = input.collect().await;
|
2020-03-10 23:00:08 +01:00
|
|
|
|
2020-06-13 10:43:21 +02:00
|
|
|
values.shuffle(&mut thread_rng());
|
2020-03-10 23:00:08 +01:00
|
|
|
|
2020-06-13 10:43:21 +02:00
|
|
|
Ok(futures::stream::iter(values.into_iter().map(ReturnSuccess::value)).to_output_stream())
|
2020-03-10 23:00:08 +01:00
|
|
|
}
|
2020-05-18 14:56:01 +02:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::Shuffle;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn examples_work_as_expected() {
|
|
|
|
use crate::examples::test as test_examples;
|
|
|
|
|
|
|
|
test_examples(Shuffle {})
|
|
|
|
}
|
|
|
|
}
|