utils: add TempDir RAII class

For tests
This commit is contained in:
Dirk-Jan C. Binnema 2022-04-09 19:14:48 +03:00
parent 100b41b257
commit a7e6d57286
2 changed files with 62 additions and 0 deletions

View File

@ -33,6 +33,7 @@
#include <iostream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <glib.h>
#include <glib/gprintf.h>
@ -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());
}

View File

@ -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__ */