From 20aa59085bae3d2d1222192e6ce4ccfec5a8eead Mon Sep 17 00:00:00 2001 From: Wind Date: Thu, 8 Feb 2024 06:42:50 +0800 Subject: [PATCH] Fix file completions which contains glob pattern (#11766) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description Fixes: https://github.com/nushell/nushell/issues/11762 The auto-completion is somehow annoying if a path contains a glob pattern, let's say if user type `ls` and it auto-completes to ls `[a] bc.txt`, and user can't list the file because it's backtick quoted. This pr is going to fix it. # User-Facing Changes ### Before ``` ❯ | ls `[a] bc.txt` `a bc` ``` ### After ``` ❯ | ls "[a] bc.txt" `a bc` ``` # Tests + Formatting Done # After Submitting NaN --- crates/nu-cli/src/completions/completion_common.rs | 12 ++++++++++++ crates/nu-cli/tests/completions.rs | 1 + tests/fixtures/quoted_completions/[a] bc.txt | 0 3 files changed, 13 insertions(+) create mode 100644 tests/fixtures/quoted_completions/[a] bc.txt diff --git a/crates/nu-cli/src/completions/completion_common.rs b/crates/nu-cli/src/completions/completion_common.rs index dfbb55102b..f4af6849f5 100644 --- a/crates/nu-cli/src/completions/completion_common.rs +++ b/crates/nu-cli/src/completions/completion_common.rs @@ -154,6 +154,18 @@ pub fn complete_item( // Fix files or folders with quotes or hashes pub fn escape_path(path: String, dir: bool) -> String { + // make glob pattern have the highest priority. + let glob_contaminated = path.contains(['[', '*', ']', '?']); + if glob_contaminated { + return if path.contains('\'') { + // decide to use double quote, also need to escape `"` in path + // or else users can't do anything with completed path either. + format!("\"{}\"", path.replace('"', r#"\""#)) + } else { + format!("'{path}'") + }; + } + let filename_contaminated = !dir && path.contains(['\'', '"', ' ', '#', '(', ')']); let dirname_contaminated = dir && path.contains(['\'', '"', ' ', '#']); let maybe_flag = path.starts_with('-'); diff --git a/crates/nu-cli/tests/completions.rs b/crates/nu-cli/tests/completions.rs index 6a0af5b116..57b0dc509f 100644 --- a/crates/nu-cli/tests/completions.rs +++ b/crates/nu-cli/tests/completions.rs @@ -584,6 +584,7 @@ fn file_completion_quoted() { let suggestions = completer.complete(target_dir, target_dir.len()); let expected_paths: Vec = vec![ + "\'[a] bc.txt\'".to_string(), "`--help`".to_string(), "`-42`".to_string(), "`-inf`".to_string(), diff --git a/tests/fixtures/quoted_completions/[a] bc.txt b/tests/fixtures/quoted_completions/[a] bc.txt new file mode 100644 index 0000000000..e69de29bb2