2020-03-10 23:00:08 +01:00
|
|
|
use crate::prelude::*;
|
2021-01-10 03:50:49 +01:00
|
|
|
use nu_engine::WholeStreamCommand;
|
2020-03-10 23:00:08 +01:00
|
|
|
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;
|
|
|
|
|
|
|
|
impl WholeStreamCommand for Shuffle {
|
|
|
|
fn name(&self) -> &str {
|
|
|
|
"shuffle"
|
|
|
|
}
|
|
|
|
|
|
|
|
fn usage(&self) -> &str {
|
|
|
|
"Shuffle rows randomly."
|
|
|
|
}
|
|
|
|
|
2021-04-12 04:35:01 +02:00
|
|
|
fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> {
|
2021-04-06 18:19:43 +02:00
|
|
|
Ok(shuffle(args))
|
2020-03-10 23:00:08 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-12 04:35:01 +02:00
|
|
|
fn shuffle(args: CommandArgs) -> ActionStream {
|
2020-06-13 10:43:21 +02:00
|
|
|
let input = args.input;
|
2021-04-06 18:19:43 +02:00
|
|
|
let mut values: Vec<Value> = input.collect();
|
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
|
|
|
|
2021-04-06 18:19:43 +02:00
|
|
|
values
|
|
|
|
.into_iter()
|
|
|
|
.map(ReturnSuccess::value)
|
2021-04-12 04:35:01 +02:00
|
|
|
.to_action_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;
|
|
|
|
|
2021-02-12 11:13:14 +01:00
|
|
|
test_examples(Shuffle {})
|
2020-05-18 14:56:01 +02:00
|
|
|
}
|
|
|
|
}
|