diff --git a/lib/utils/mu-utils.cc b/lib/utils/mu-utils.cc index ce4c4cfd..1c02ed06 100644 --- a/lib/utils/mu-utils.cc +++ b/lib/utils/mu-utils.cc @@ -33,6 +33,7 @@ #include #include #include +#include #include #include @@ -40,6 +41,7 @@ #include "mu-utils.hh" #include "mu-util.h" #include "mu-str.h" +#include "mu-error.hh" using namespace Mu; @@ -582,6 +584,7 @@ Mu::canonicalize_filename(const std::string& path, const std::string& relative_t return rv; } + void Mu::allow_warnings() { @@ -589,3 +592,31 @@ Mu::allow_warnings() [](const char*, GLogLevelFlags, const char*, gpointer) { return FALSE; }, {}); } + + + +Mu::TempDir::TempDir() +{ + GError *err{}; + gchar *tmpdir = g_dir_make_tmp("mu-tmp-XXXXXX", &err); + if (!tmpdir) + throw Mu::Error(Error::Code::File, &err, + "failed to create temporary directory"); + + path_ = tmpdir; + g_free(tmpdir); + + g_debug("created '%s'", path_.c_str()); +} + +Mu::TempDir::~TempDir() +{ + if (::access(path_.c_str(), F_OK) != 0) + return; /* nothing to do */ + + /* ugly */ + const auto cmd{format("/bin/rm -rf '%s'", path_.c_str())}; + ::system(cmd.c_str()); + + g_debug("removed '%s'", path_.c_str()); +} diff --git a/lib/utils/mu-utils.hh b/lib/utils/mu-utils.hh index 69bf348d..16a0f1ce 100644 --- a/lib/utils/mu-utils.hh +++ b/lib/utils/mu-utils.hh @@ -443,6 +443,37 @@ private: */ void allow_warnings(); + +/** + * For unit-tests, a RAII tempdir. + * + */ +struct TempDir { + /** + * Construct a temporary directory + */ + TempDir(); + + /** + * DTOR; removes the temporary directory + * + * + * @return + */ + ~TempDir(); + + /** + * Path to the temporary directory + * + * @return the path. + * + * + */ + const std::string& path() {return path_; } +private: + std::string path_; +}; + } // namespace Mu #endif /* __MU_UTILS_HH__ */