/* TEMP-DIR.hpp - automatic allocation of a temporary working directory Copyright (C) 2024, Hermann Vosseler   **Lumiera** is free software; you can redistribute it and/or modify it   under the terms of the GNU General Public License as published by the   Free Software Foundation; either version 2 of the License, or (at your   option) any later version. See the file COPYING for further details. */ /** @file temp-dir.hpp ** Manage a temporary directory for storage, with automated clean-up. ** @see TempDir_test */ #ifndef TESTSUPPORT_TEMP_DIR_H #define TESTSUPPORT_TEMP_DIR_H #include "lib/error.hpp" #include "lib/nocopy.hpp" #include "lib/random.hpp" #include "include/limits.hpp" #include "lib/format-string.hpp" #include "lib/format-obj.hpp" #include "lib/file.hpp" #include "lib/util.hpp" #include #include namespace test{ namespace error = lumiera::error; using util::_Fmt; using util::isnil; using std::string; namespace { lib::Literal TEMPFILE_PREFIX = "Lux"; } /** * A RAII style temporary directory. */ class TempDir : util::MoveOnly { fs::path loc_; public: TempDir() : loc_{establishNewDirectory()} { } ~TempDir() { if (fs::exists (loc_)) destroyTempDirectory(); } operator fs::path const& () const { return loc_; } fs::path makeFile (string name ="") { if (isnil (name)) return establishNewFile (string{TEMPFILE_PREFIX}); auto newFile = loc_ / name; if (fs::exists (newFile)) return establishNewFile (name); std::ofstream{newFile}; if (fs::exists (newFile) and fs::is_empty(newFile)) return newFile; // throw error::Fatal{_Fmt{"Failed to create unique new file %s in TempDir."} % newFile}; } private: static fs::path establishNewDirectory() { auto tmpDir = fs::temp_directory_path(); for (uint attempt=0; attempt