]> xenbits.xensource.com Git - libvirt.git/commitdiff
virfile: Introduce virDirIsEmpty()
authorMichal Privoznik <mprivozn@redhat.com>
Fri, 21 Jul 2023 08:41:35 +0000 (10:41 +0200)
committerMichal Privoznik <mprivozn@redhat.com>
Fri, 21 Jul 2023 12:55:18 +0000 (14:55 +0200)
There might be cases where we want to know whether given
directory is empty or not. Introduce a helper for that:
virDirIsEmpty().

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
Reviewed-by: Ján Tomko <jtomko@redhat.com>
src/libvirt_private.syms
src/util/virfile.c
src/util/virfile.h

index 3071dec13a77520b9df6e8c6f68f09840b5e92c2..da60c965ddcad671307f95eef230dc245640b00a 100644 (file)
@@ -2271,6 +2271,7 @@ safezero;
 virBuildPathInternal;
 virDirClose;
 virDirCreate;
+virDirIsEmpty;
 virDirOpen;
 virDirOpenIfExists;
 virDirOpenQuiet;
index 6b4d4c3522f9d08b9e4e21f697c9849a03c7752f..7c44a2a96310df516a1734e2ce5557fcf5ba3261 100644 (file)
@@ -3036,6 +3036,45 @@ void virDirClose(DIR *dirp)
     closedir(dirp); /* exempt from syntax-check */
 }
 
+/**
+ * virDirIsEmpty:
+ * @path: path to the directory
+ * @hidden: whether hidden files matter
+ *
+ * Check whether given directory (@path) is empty, i.e. it
+ * contains just the usual entries '.' and '..'. Hidden files are
+ * ignored unless @hidden is true. IOW, a directory containing
+ * nothing but hidden files is considered empty if @hidden is
+ * false and not empty if @hidden is true.
+ *
+ * Returns: 1 if the directory is empty,
+ *          0 if the directory is not empty,
+ *         -1 otherwise (no error reported).
+ */
+int virDirIsEmpty(const char *path,
+                  bool hidden)
+{
+    g_autoptr(DIR) dir = NULL;
+    struct dirent *ent;
+    int direrr;
+
+    if (virDirOpenQuiet(&dir, path) < 0)
+        return -1;
+
+    while ((direrr = virDirRead(dir, &ent, NULL)) > 0) {
+        /* virDirRead() skips over '.' and '..' so here we have
+         * actual directory entry. */
+        if (!hidden ||
+            (hidden && ent->d_name[0] != '.'))
+            return 0;
+    }
+
+    if (direrr < 0)
+        return -1;
+
+    return 1;
+}
+
 
 /*
  * virFileChownFiles:
index 6a14173625009939dff96d322a37570acd858eea..b75a7cc53b3d26dd08065e03801c9550aafc40df 100644 (file)
@@ -283,6 +283,9 @@ int virDirRead(DIR *dirp, struct dirent **ent, const char *dirname)
     ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2) G_GNUC_WARN_UNUSED_RESULT;
 void virDirClose(DIR *dirp);
 G_DEFINE_AUTOPTR_CLEANUP_FUNC(DIR, virDirClose);
+int virDirIsEmpty(const char *path,
+                  bool hidden)
+    ATTRIBUTE_NONNULL(1) G_GNUC_WARN_UNUSED_RESULT;
 
 int virFileMakeParentPath(const char *path) G_GNUC_WARN_UNUSED_RESULT;