From 48f049e33cb34dac78fdcfdda79d9fd56bbaffa6 Mon Sep 17 00:00:00 2001 From: Joel Rosdahl Date: Tue, 8 Sep 2020 20:05:43 +0200 Subject: [PATCH] Add Util::ensure_dir_exists --- src/Util.cpp | 8 ++++++++ src/Util.hpp | 3 +++ unittest/test_Util.cpp | 15 +++++++++++++++ 3 files changed, 26 insertions(+) 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"); -- 2.47.3