From 19772f82aaecd21db87f4d14ac085130c3b7f01f Mon Sep 17 00:00:00 2001 From: Dmitry Starostin Date: Sat, 24 Aug 2019 23:31:45 +0300 Subject: [PATCH] Add --reverse option for sort-by --- README.md | 2 +- src/commands/sort_by.rs | 14 +++++++++++--- tests/filters_test.rs | 11 +++++++++++ 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 7d9e102347..317df72ed5 100644 --- a/README.md +++ b/README.md @@ -185,7 +185,7 @@ Nu adheres closely to a set of goals that make up its design philosophy. As feat | pick ...columns | Down-select table to only these columns | | reject ...columns | Remove the given columns from the table | | get column-or-column-path | Open given cells as text | -| sort-by ...columns | Sort by the given columns | +| sort-by ...columns (--reverse) | Sort by the given columns | | where condition | Filter table to match the condition | | inc (field) | Increment a value or version. Optional use the field of a table | | add field value | Add a new field to the table | diff --git a/src/commands/sort_by.rs b/src/commands/sort_by.rs index 52d97a5952..820e0a471d 100644 --- a/src/commands/sort_by.rs +++ b/src/commands/sort_by.rs @@ -18,7 +18,7 @@ impl WholeStreamCommand for SortBy { } fn signature(&self) -> Signature { - Signature::build("sort-by") + Signature::build("sort-by").switch("reverse") } } @@ -37,13 +37,21 @@ fn sort_by(args: CommandArgs, registry: &CommandRegistry) -> Result>(); + let reverse = args.has("reverse"); let output = output.map(move |mut vec| { - vec.sort_by_key(|item| { + let calc_key = |item: &Tagged| { fields .iter() .map(|f| item.get_data_by_key(f).map(|i| i.clone())) .collect::>>>() - }); + }; + if reverse { + vec.sort_by_cached_key(|item| { + std::cmp::Reverse(calc_key(item)) + }); + } else { + vec.sort_by_cached_key(calc_key); + } vec.into_iter().collect::>() }); diff --git a/tests/filters_test.rs b/tests/filters_test.rs index 8b0e40bef3..20eba8050c 100644 --- a/tests/filters_test.rs +++ b/tests/filters_test.rs @@ -57,6 +57,17 @@ fn can_sort_by_column() { assert_eq!(output, "description"); } +#[test] +fn can_sort_by_column_reverse() { + nu!( + output, + cwd("tests/fixtures/formats"), + "open cargo_sample.toml --raw | lines | skip 1 | first 4 | split-column \"=\" | sort-by Column1 --reverse | skip 1 | first 1 | get Column1 | trim | echo $it" + ); + + assert_eq!(output, "name"); +} + #[test] fn can_split_by_column() { nu!(