Refactor MkdirP out into a utility.
We want to use it again!
Change-Id: Iec72840e8fa1a8915e8176842f865a2f8acbfd93
diff --git a/aos/util/file.cc b/aos/util/file.cc
index af1f85b..b334ded 100644
--- a/aos/util/file.cc
+++ b/aos/util/file.cc
@@ -1,6 +1,8 @@
#include "aos/util/file.h"
#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
#include <unistd.h>
#include <string_view>
@@ -46,5 +48,23 @@
}
}
+void MkdirP(std::string_view path, mode_t mode) {
+ auto last_slash_pos = path.find_last_of("/");
+
+ std::string folder(last_slash_pos == std::string_view::npos
+ ? std::string_view("")
+ : path.substr(0, last_slash_pos));
+ if (folder.empty()) return;
+ MkdirP(folder, mode);
+ const int result = mkdir(folder.c_str(), mode);
+ if (result == -1 && errno == EEXIST) {
+ VLOG(2) << folder << " already exists";
+ return;
+ } else {
+ VLOG(1) << "Created " << folder;
+ }
+ PCHECK(result == 0) << ": Error creating " << folder;
+}
+
} // namespace util
} // namespace aos
diff --git a/aos/util/file.h b/aos/util/file.h
index 3aebd87..d6724af 100644
--- a/aos/util/file.h
+++ b/aos/util/file.h
@@ -15,6 +15,8 @@
void WriteStringToFileOrDie(const std::string_view filename,
const std::string_view contents);
+void MkdirP(std::string_view path, mode_t mode);
+
} // namespace util
} // namespace aos