From 62f0fa818d9744c0a8b9803dadb7a52329906a2e Mon Sep 17 00:00:00 2001 From: Tim Schumacher Date: Mon, 14 Mar 2022 11:19:10 +0100 Subject: [PATCH] LibCore: Add File::ensure_directories() --- Userland/Libraries/LibCore/File.cpp | 21 +++++++++++++-------- Userland/Libraries/LibCore/File.h | 1 + 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/Userland/Libraries/LibCore/File.cpp b/Userland/Libraries/LibCore/File.cpp index d03837d9f5..9ae04bc028 100644 --- a/Userland/Libraries/LibCore/File.cpp +++ b/Userland/Libraries/LibCore/File.cpp @@ -183,17 +183,22 @@ String File::real_path_for(String const& filename) bool File::ensure_parent_directories(String const& path) { - VERIFY(path.starts_with("/")); - - int saved_errno = 0; - ScopeGuard restore_errno = [&saved_errno] { errno = saved_errno; }; - char* parent_buffer = strdup(path.characters()); ScopeGuard free_buffer = [parent_buffer] { free(parent_buffer); }; char const* parent = dirname(parent_buffer); - int rc = mkdir(parent, 0755); + return ensure_directories(parent); +} + +bool File::ensure_directories(String const& path) +{ + VERIFY(path.starts_with("/")); + + int saved_errno = 0; + ScopeGuard restore_errno = [&saved_errno] { errno = saved_errno; }; + + int rc = mkdir(path.characters(), 0755); saved_errno = errno; if (rc == 0 || errno == EEXIST) @@ -202,12 +207,12 @@ bool File::ensure_parent_directories(String const& path) if (errno != ENOENT) return false; - bool ok = ensure_parent_directories(parent); + bool ok = ensure_parent_directories(path); saved_errno = errno; if (!ok) return false; - rc = mkdir(parent, 0755); + rc = mkdir(path.characters(), 0755); saved_errno = errno; return rc == 0; } diff --git a/Userland/Libraries/LibCore/File.h b/Userland/Libraries/LibCore/File.h index 6c59972fdd..146a3ae239 100644 --- a/Userland/Libraries/LibCore/File.h +++ b/Userland/Libraries/LibCore/File.h @@ -38,6 +38,7 @@ public: static bool exists(String const& filename); static ErrorOr size(String const& filename); static bool ensure_parent_directories(String const& path); + static bool ensure_directories(String const& path); static String current_working_directory(); static String absolute_path(String const& path);