From: Joel Rosdahl Date: Tue, 8 Sep 2020 18:05:43 +0000 (+0200) Subject: Add Util::ensure_dir_exists X-Git-Tag: v4.0~118 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=48f049e33cb34dac78fdcfdda79d9fd56bbaffa6;p=thirdparty%2Fccache.git Add Util::ensure_dir_exists --- diff --git a/src/Util.cpp b/src/Util.cpp index 644864b9d..78e3d8445 100644 --- a/src/Util.cpp +++ b/src/Util.cpp @@ -556,6 +556,14 @@ format_parsable_size_with_suffix(uint64_t size) } } +void +ensure_dir_exists(nonstd::string_view dir) +{ + if (!create_dir(dir)) { + throw Fatal("Failed to create directory {}: {}", dir, strerror(errno)); + } +} + std::string get_actual_cwd() { diff --git a/src/Util.hpp b/src/Util.hpp index c00078031..834f9f74e 100644 --- a/src/Util.hpp +++ b/src/Util.hpp @@ -124,6 +124,9 @@ ends_with(nonstd::string_view string, nonstd::string_view suffix) return string.ends_with(suffix); } +// Like create_dir but throws Fatal on error. +void ensure_dir_exists(nonstd::string_view dir); + // Expand all instances of $VAR or ${VAR}, where VAR is an environment variable, // in `str`. Throws `Error` if one of the environment variables. [[nodiscard]] std::string expand_environment_variables(const std::string& str); diff --git a/unittest/test_Util.cpp b/unittest/test_Util.cpp index 077a8660a..154ab509e 100644 --- a/unittest/test_Util.cpp +++ b/unittest/test_Util.cpp @@ -163,6 +163,21 @@ TEST_CASE("Util::ends_with") CHECK_FALSE(Util::ends_with("x", "xy")); } +TEST_CASE("Util::ensure_dir_exists") +{ + TestContext test_context; + + CHECK_NOTHROW(Util::ensure_dir_exists("/")); + + CHECK_NOTHROW(Util::ensure_dir_exists("create/dir")); + CHECK(Stat::stat("create/dir").is_directory()); + + Util::write_file("create/dir/file", ""); + CHECK_THROWS_WITH( + Util::ensure_dir_exists("create/dir/file"), + "Failed to create directory create/dir/file: Not a directory"); +} + TEST_CASE("Util::expand_environment_variables") { Util::setenv("FOO", "bar");