From 217eb4ed703c60d0ab96a069d851cba5ec3e8894 Mon Sep 17 00:00:00 2001 From: Wind Date: Thu, 12 Sep 2024 01:45:39 +0800 Subject: [PATCH] fix path exists on a non-directory file (#13763) # Description Fixes: #13460 The issue is caused by `try_exists` method on path, it will return `Err(NotADirectory)` if user tried to check for a path under a regular file. To fix it, I think it's ok to use `exists` rather than `try_exists`, although [Path::exists()](https://doc.rust-lang.org/std/path/struct.Path.html#method.exists) only checks whether or not a path was both found and readable. I think it's ok, and we can add this information under `extra_description`. # User-Facing Changes The following code will no longer raise error: ``` touch a; 'a/b' | path exists ``` # Tests + Formatting Added 1 test. --- crates/nu-command/src/path/exists.rs | 5 +++-- crates/nu-command/tests/commands/path/exists.rs | 12 ++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/crates/nu-command/src/path/exists.rs b/crates/nu-command/src/path/exists.rs index f00e6c17ef..3e40bef28a 100644 --- a/crates/nu-command/src/path/exists.rs +++ b/crates/nu-command/src/path/exists.rs @@ -39,7 +39,8 @@ impl Command for SubCommand { fn extra_description(&self) -> &str { r#"This only checks if it is possible to either `open` or `cd` to the given path. -If you need to distinguish dirs and files, please use `path type`."# +If you need to distinguish dirs and files, please use `path type`. +Also note that if you don't have a permission to a directory of a path, false will be returned"# } fn is_const(&self) -> bool { @@ -147,7 +148,7 @@ fn exists(path: &Path, span: Span, args: &Arguments) -> Value { |_| Ok(true), ) } else { - path.try_exists() + Ok(path.exists()) }; Value::bool( match exists { diff --git a/crates/nu-command/tests/commands/path/exists.rs b/crates/nu-command/tests/commands/path/exists.rs index 96fa02c0e8..faafac910c 100644 --- a/crates/nu-command/tests/commands/path/exists.rs +++ b/crates/nu-command/tests/commands/path/exists.rs @@ -64,6 +64,18 @@ fn const_path_exists() { assert_eq!(actual.out, "true"); } +#[test] +fn path_exists_under_a_non_directory() { + Playground::setup("path_exists_6", |dirs, _| { + let actual = nu!( + cwd: dirs.test(), + "touch test_file; 'test_file/aaa' | path exists" + ); + assert_eq!(actual.out, "false"); + assert!(actual.err.is_empty()); + }) +} + #[test] fn test_check_symlink_exists() { use nu_test_support::{nu, playground::Playground};