Add path_exists() function (#1106)

This commit is contained in:
Damian Kula 2022-02-21 22:45:30 +01:00 committed by GitHub
parent b4a0a8090d
commit 6271e94bc9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 30 additions and 0 deletions

View File

@ -981,6 +981,10 @@ These functions can fail, for example if a path does not have an extension, whic
- `clean(path)` - Simplify `path` by removing extra path separators, intermediate `.` components, and `..` where possible. `clean("foo//bar")` is `foo/bar`, `clean("foo/..")` is `.`, `clean("foo/./bar")` is `foo/bar`. - `clean(path)` - Simplify `path` by removing extra path separators, intermediate `.` components, and `..` where possible. `clean("foo//bar")` is `foo/bar`, `clean("foo/..")` is `.`, `clean("foo/./bar")` is `foo/bar`.
#### Filesystem Access
- `path_exists(path)` - Returns `true` if the path points at an existing entity and `false` otherwise. Traverses symbolic links, and returns `false` if the path is inaccessible or points to a broken symlink.
### Command Evaluation Using Backticks ### Command Evaluation Using Backticks
Backticks can be used to store the result of commands: Backticks can be used to store the result of commands:

View File

@ -30,6 +30,7 @@ lazy_static! {
("os", Nullary(os)), ("os", Nullary(os)),
("os_family", Nullary(os_family)), ("os_family", Nullary(os_family)),
("parent_directory", Unary(parent_directory)), ("parent_directory", Unary(parent_directory)),
("path_exists", Unary(path_exists)),
("quote", Unary(quote)), ("quote", Unary(quote)),
("replace", Ternary(replace)), ("replace", Ternary(replace)),
("trim", Unary(trim)), ("trim", Unary(trim)),
@ -210,6 +211,10 @@ fn parent_directory(_context: &FunctionContext, path: &str) -> Result<String, St
.ok_or_else(|| format!("Could not extract parent directory from `{}`", path)) .ok_or_else(|| format!("Could not extract parent directory from `{}`", path))
} }
fn path_exists(_context: &FunctionContext, path: &str) -> Result<String, String> {
Ok(Utf8Path::new(path).exists().to_string())
}
fn quote(_context: &FunctionContext, s: &str) -> Result<String, String> { fn quote(_context: &FunctionContext, s: &str) -> Result<String, String> {
Ok(format!("'{}'", s.replace('\'', "'\\''"))) Ok(format!("'{}'", s.replace('\'', "'\\''")))
} }

View File

@ -382,3 +382,24 @@ fn join_argument_count_error() {
.status(EXIT_FAILURE) .status(EXIT_FAILURE)
.run(); .run();
} }
#[test]
fn test_path_exists_filepath_exist() {
Test::new()
.tree(tree! {
testfile: ""
})
.justfile("x := path_exists('testfile')")
.args(&["--evaluate", "x"])
.stdout("true")
.run();
}
#[test]
fn test_path_exists_filepath_doesnt_exist() {
Test::new()
.justfile("x := path_exists('testfile')")
.args(&["--evaluate", "x"])
.stdout("false")
.run();
}