From 6fc082f6e9d26fe017c30d117b5f7ab34b0cc0ec Mon Sep 17 00:00:00 2001 From: Darren Schroeder <343840+fdncred@users.noreply.github.com> Date: Sat, 12 Feb 2022 20:48:50 -0600 Subject: [PATCH] fix case insensitive sort (#4449) * fix case insensitive search * fixed test * tweak --- crates/nu-command/src/filters/sort_by.rs | 27 ++++++++++++++++----- crates/nu-command/tests/commands/sort_by.rs | 2 +- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/crates/nu-command/src/filters/sort_by.rs b/crates/nu-command/src/filters/sort_by.rs index ddbbfef8..045221b6 100644 --- a/crates/nu-command/src/filters/sort_by.rs +++ b/crates/nu-command/src/filters/sort_by.rs @@ -138,11 +138,6 @@ pub fn sort( insensitive: bool, config: &Config, ) -> Result<(), ShellError> { - let should_sort_case_insensitively = insensitive - && vec - .iter() - .all(|x| matches!(x.get_type(), nu_protocol::Type::String)); - match &vec[0] { Value::Record { cols, @@ -158,6 +153,26 @@ pub fn sort( return Err(ShellError::CantFindColumn(call.head, call.head)); } + // check to make sure each value in each column in the record + // that we asked for is a string. So, first collect all the columns + // that we asked for into vals, then later make sure they're all + // strings. + let mut vals = vec![]; + for item in vec.iter() { + for col in &columns { + let val = match item.get_data_by_key(col) { + Some(v) => v, + None => Value::nothing(Span::test_data()), + }; + vals.push(val); + } + } + + let should_sort_case_insensitively = insensitive + && vals + .iter() + .all(|x| matches!(x.get_type(), nu_protocol::Type::String)); + vec.sort_by(|a, b| { process( a, @@ -173,7 +188,7 @@ pub fn sort( } _ => { vec.sort_by(|a, b| { - if should_sort_case_insensitively { + if insensitive { let lowercase_left = Value::string( a.into_string("", config).to_ascii_lowercase(), Span::test_data(), diff --git a/crates/nu-command/tests/commands/sort_by.rs b/crates/nu-command/tests/commands/sort_by.rs index e7eb5716..5f3e43a8 100644 --- a/crates/nu-command/tests/commands/sort_by.rs +++ b/crates/nu-command/tests/commands/sort_by.rs @@ -113,7 +113,7 @@ fn ls_sort_by_name_insensitive() { "# )); - let json_output = r#"[{"name": "B.txt"},{"name": "C"},{"name": "a.txt"}]"#; + let json_output = r#"[{"name": "a.txt"},{"name": "B.txt"},{"name": "C"}]"#; assert_eq!(actual.out, json_output); }