From 1c0bfd24b18d67a6fa4bc42185cdc8d5af3cb804 Mon Sep 17 00:00:00 2001
From: Colin Walters <walters@verbum.org>
Date: Wed, 19 Jul 2017 11:57:35 -0400
Subject: [PATCH] dirfd: Add glnx_ensure_dir()

Another one where we have a lot of inlines in ostree at least. Not the same as
`glnx_shutil_mkdir_p_at()` since in these cases we don't want automatic
intermediate dirs, and it's cheaper to just call `mkdirat()` and handle `EEXIST`
rather than do a `stat()` first.
---
 glnx-dirfd.h  | 28 ++++++++++++++++++++++++++++
 glnx-shutil.c |  2 ++
 2 files changed, 30 insertions(+)

diff --git a/glnx-dirfd.h b/glnx-dirfd.h
index 581b3032e..4824bc4b3 100644
--- a/glnx-dirfd.h
+++ b/glnx-dirfd.h
@@ -83,6 +83,34 @@ char *glnx_fdrel_abspath (int         dfd,
 
 void glnx_gen_temp_name (gchar *tmpl);
 
+/**
+ * glnx_ensure_dir:
+ * @dfd: directory fd
+ * @path: Directory path
+ * @mode: Mode
+ * @error: Return location for a #GError, or %NULL
+ *
+ * Wrapper around mkdirat() which ignores adds #GError support, ensures that
+ * it retries on %EINTR, and also ignores `EEXIST`.
+ *
+ * See also `glnx_shutil_mkdir_p_at()` for recursive handling.
+ *
+ * Returns: %TRUE on success, %FALSE otherwise
+ */
+static inline gboolean
+glnx_ensure_dir (int           dfd,
+                 const char   *path,
+                 mode_t        mode,
+                 GError      **error)
+{
+  if (TEMP_FAILURE_RETRY (mkdirat (dfd, path, mode)) != 0)
+    {
+      if (G_UNLIKELY (errno != EEXIST))
+        return glnx_throw_errno_prefix (error, "mkdirat(%s)", path);
+    }
+  return TRUE;
+}
+
 gboolean glnx_mkdtempat (int dfd,
                          gchar *tmpl,
                          int mode,
diff --git a/glnx-shutil.c b/glnx-shutil.c
index 2e02eea45..9124d7a4f 100644
--- a/glnx-shutil.c
+++ b/glnx-shutil.c
@@ -185,6 +185,8 @@ mkdir_p_at_internal (int              dfd,
  *
  * Similar to g_mkdir_with_parents(), except operates relative to the
  * directory fd @dfd.
+ *
+ * See also glnx_ensure_dir() for a non-recursive version.
  */
 gboolean
 glnx_shutil_mkdir_p_at (int                   dfd,
-- 
GitLab