diff options
author | Ilya K <me@0upti.me> | 2024-04-11 13:45:46 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@lix> | 2024-04-11 13:45:46 +0000 |
commit | d106bb553bc034c4ae2c1e7f55e7c97417c84a98 (patch) | |
tree | 47ddd492bc94fd91b4e4a33d2817a1ef159fa158 /src/libutil | |
parent | a0875f6adf5f7b8d3c3dced7ccff35ef4b22c864 (diff) | |
parent | aeee22e5a17404b10dd14b5289e302eaf546e1aa (diff) |
Merge "Merge pull request #10362 from obsidiansystems/maybeLstat" into main
Diffstat (limited to 'src/libutil')
-rw-r--r-- | src/libutil/util.cc | 20 | ||||
-rw-r--r-- | src/libutil/util.hh | 6 |
2 files changed, 19 insertions, 7 deletions
diff --git a/src/libutil/util.cc b/src/libutil/util.cc index 5cd4df8e6..dc724db3e 100644 --- a/src/libutil/util.cc +++ b/src/libutil/util.cc @@ -256,16 +256,22 @@ struct stat lstat(const Path & path) return st; } +std::optional<struct stat> maybeLstat(const Path & path) +{ + std::optional<struct stat> st{std::in_place}; + if (lstat(path.c_str(), &*st)) + { + if (errno == ENOENT || errno == ENOTDIR) + st.reset(); + else + throw SysError("getting status of '%s'", path); + } + return st; +} bool pathExists(const Path & path) { - int res; - struct stat st; - res = lstat(path.c_str(), &st); - if (!res) return true; - if (errno != ENOENT && errno != ENOTDIR) - throw SysError("getting status of %1%", path); - return false; + return maybeLstat(path).has_value(); } bool pathAccessible(const Path & path) diff --git a/src/libutil/util.hh b/src/libutil/util.hh index 29a70447e..61df6c4f8 100644 --- a/src/libutil/util.hh +++ b/src/libutil/util.hh @@ -115,6 +115,12 @@ struct stat stat(const Path & path); struct stat lstat(const Path & path); /** + * `lstat` the given path if it exists. + * @return std::nullopt if the path doesn't exist, or an optional containing the result of `lstat` otherwise + */ +std::optional<struct stat> maybeLstat(const Path & path); + +/** * @return true iff the given path exists. */ bool pathExists(const Path & path); |