summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorColin Walters <walters@verbum.org>2012-11-29 16:36:56 -0500
committerColin Walters <walters@verbum.org>2012-11-29 16:36:56 -0500
commitab2588da8442fc6135af13ee624dd91b73a7051c (patch)
tree6cfc5e4e0b0931631d3d03658302f4f42a691f88
parent1332d9713365a53fae76570a3c484753f9bcbb30 (diff)
downloadlibgsystem-ab2588da8442fc6135af13ee624dd91b73a7051c.tar.gz
fileutils: Add gs_file_ensure_directory
This is a very common operation in build systems, etc.
-rw-r--r--gsystem-file-utils.c51
-rw-r--r--gsystem-file-utils.h6
2 files changed, 57 insertions, 0 deletions
diff --git a/gsystem-file-utils.c b/gsystem-file-utils.c
index 5277c27..0ff6abd 100644
--- a/gsystem-file-utils.c
+++ b/gsystem-file-utils.c
@@ -188,3 +188,54 @@ gs_file_unlink (GFile *path,
}
return TRUE;
}
+
+/**
+ * gs_file_ensure_directory:
+ * @dir: Path to create as directory
+ * @with_parents: Also create parent directories
+ * @cancellable: a #GCancellable
+ * @error: a #GError
+ *
+ * Like g_file_make_directory(), except does not throw an error if the
+ * directory already exists.
+ */
+gboolean
+gs_file_ensure_directory (GFile *dir,
+ gboolean with_parents,
+ GCancellable *cancellable,
+ GError **error)
+{
+ gboolean ret = FALSE;
+ GError *temp_error = NULL;
+
+ if (!g_file_make_directory (dir, cancellable, &temp_error))
+ {
+ if (with_parents &&
+ g_error_matches (temp_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
+ {
+ gs_lobj GFile *parent = NULL;
+
+ g_clear_error (&temp_error);
+
+ parent = g_file_get_parent (dir);
+ if (parent)
+ {
+ if (!gs_file_ensure_directory (parent, TRUE, cancellable, error))
+ goto out;
+ }
+ if (!gs_file_ensure_directory (dir, FALSE, cancellable, error))
+ goto out;
+ }
+ else if (!g_error_matches (temp_error, G_IO_ERROR, G_IO_ERROR_EXISTS))
+ {
+ g_propagate_error (error, temp_error);
+ goto out;
+ }
+ else
+ g_clear_error (&temp_error);
+ }
+
+ ret = TRUE;
+ out:
+ return ret;
+}
diff --git a/gsystem-file-utils.h b/gsystem-file-utils.h
index 080abc3..ff87c6e 100644
--- a/gsystem-file-utils.h
+++ b/gsystem-file-utils.h
@@ -42,6 +42,12 @@ gboolean gs_file_unlink (GFile *path,
GCancellable *cancellable,
GError **error);
+gboolean gs_file_ensure_directory (GFile *dir,
+ gboolean with_parents,
+ GCancellable *cancellable,
+ GError **error);
+
+
G_END_DECLS
#endif