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-12-18 08:53:49 +01:00
|
|
|
async fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|
|
|
shuffle(args).await
|
2020-03-10 23:00:08 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-18 08:53:49 +01:00
|
|
|
async fn shuffle(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
2020-06-13 10:43:21 +02:00
|
|
|
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 {
|
2020-10-03 16:06:02 +02:00
|
|
|
use super::ShellError;
|
2020-05-18 14:56:01 +02:00
|
|
|
use super::Shuffle;
|
|
|
|
|
|
|
|
#[test]
|
2020-10-03 16:06:02 +02:00
|
|
|
fn examples_work_as_expected() -> Result<(), ShellError> {
|
2020-05-18 14:56:01 +02:00
|
|
|
use crate::examples::test as test_examples;
|
|
|
|
|
2020-10-03 16:06:02 +02:00
|
|
|
Ok(test_examples(Shuffle {})?)
|
2020-05-18 14:56:01 +02:00
|
|
|
}
|
|
|
|
}
|