diff options
author | John Ericson <John.Ericson@Obsidian.Systems> | 2024-03-30 11:23:29 -0400 |
---|---|---|
committer | K900 <me@0upti.me> | 2024-04-11 15:43:41 +0300 |
commit | aeee22e5a17404b10dd14b5289e302eaf546e1aa (patch) | |
tree | 3bed2463ffd9916104b95fcb58be5537d65f800c /src/libutil | |
parent | 99845e0e01eaa2120b10c22591c43c4305f5ba51 (diff) |
Merge pull request #10362 from obsidiansystems/maybeLstat
Factor out `nix::maybeLstat`
(cherry-picked from commit 9b88e5284608116b7db0dbd3d5dd7a33b90d52d7)
Change-Id: Id890525e847c890fad6593c594772826ac4d1d50
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); |