2019-08-19 07:16:39 +02:00
|
|
|
use crate::commands::WholeStreamCommand;
|
2019-05-17 17:55:50 +02:00
|
|
|
use crate::errors::ShellError;
|
|
|
|
use crate::prelude::*;
|
|
|
|
|
2019-08-19 07:16:39 +02:00
|
|
|
pub struct SortBy;
|
|
|
|
|
|
|
|
impl WholeStreamCommand for SortBy {
|
|
|
|
fn run(
|
|
|
|
&self,
|
|
|
|
args: CommandArgs,
|
|
|
|
registry: &CommandRegistry,
|
|
|
|
) -> Result<OutputStream, ShellError> {
|
|
|
|
sort_by(args, registry)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn name(&self) -> &str {
|
|
|
|
"sort-by"
|
|
|
|
}
|
|
|
|
|
|
|
|
fn signature(&self) -> Signature {
|
2019-08-24 22:31:45 +02:00
|
|
|
Signature::build("sort-by").switch("reverse")
|
2019-08-19 07:16:39 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn sort_by(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
|
2019-07-24 00:22:11 +02:00
|
|
|
let args = args.evaluate_once(registry)?;
|
|
|
|
let (input, args) = args.parts();
|
|
|
|
|
|
|
|
let fields: Result<Vec<_>, _> = args
|
|
|
|
.positional
|
|
|
|
.iter()
|
|
|
|
.flatten()
|
|
|
|
.map(|a| a.as_string())
|
|
|
|
.collect();
|
|
|
|
|
2019-05-22 09:12:03 +02:00
|
|
|
let fields = fields?;
|
2019-05-17 17:55:50 +02:00
|
|
|
|
2019-07-24 00:22:11 +02:00
|
|
|
let output = input.values.collect::<Vec<_>>();
|
2019-05-17 17:55:50 +02:00
|
|
|
|
2019-08-24 22:31:45 +02:00
|
|
|
let reverse = args.has("reverse");
|
2019-05-23 09:23:06 +02:00
|
|
|
let output = output.map(move |mut vec| {
|
2019-08-24 22:31:45 +02:00
|
|
|
let calc_key = |item: &Tagged<Value>| {
|
2019-05-23 09:23:06 +02:00
|
|
|
fields
|
|
|
|
.iter()
|
2019-07-08 18:44:53 +02:00
|
|
|
.map(|f| item.get_data_by_key(f).map(|i| i.clone()))
|
2019-08-01 03:58:42 +02:00
|
|
|
.collect::<Vec<Option<Tagged<Value>>>>()
|
2019-08-24 22:31:45 +02:00
|
|
|
};
|
|
|
|
if reverse {
|
|
|
|
vec.sort_by_cached_key(|item| {
|
|
|
|
std::cmp::Reverse(calc_key(item))
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
vec.sort_by_cached_key(calc_key);
|
|
|
|
}
|
2019-05-22 09:12:03 +02:00
|
|
|
|
2019-07-03 22:31:15 +02:00
|
|
|
vec.into_iter().collect::<VecDeque<_>>()
|
2019-05-23 09:23:06 +02:00
|
|
|
});
|
2019-05-17 17:55:50 +02:00
|
|
|
|
2019-07-03 22:31:15 +02:00
|
|
|
Ok(output.flatten_stream().from_input_stream())
|
2019-05-17 17:55:50 +02:00
|
|
|
}
|