aboutsummaryrefslogtreecommitdiff
path: root/src/libutil
diff options
context:
space:
mode:
Diffstat (limited to 'src/libutil')
-rw-r--r--src/libutil/util.cc20
-rw-r--r--src/libutil/util.hh6
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);