Merge pull request #399 from incrop/sort-by-reverse

Add --reverse option for sort-by
This commit is contained in:
Jonathan Turner 2019-08-25 09:51:25 +12:00 committed by GitHub
commit 236e9ac81e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 23 additions and 4 deletions

View File

@ -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 |

View File

@ -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<OutputStream
let output = input.values.collect::<Vec<_>>();
let reverse = args.has("reverse");
let output = output.map(move |mut vec| {
vec.sort_by_key(|item| {
let calc_key = |item: &Tagged<Value>| {
fields
.iter()
.map(|f| item.get_data_by_key(f).map(|i| i.clone()))
.collect::<Vec<Option<Tagged<Value>>>>()
};
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::<VecDeque<_>>()
});

View File

@ -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!(