Peano
Loading...
Searching...
No Matches
temporary-directory.h
Go to the documentation of this file.
1#ifndef APPARENT_HORIZON_FINDER_TEST_TEMPORARY_DIRECTORY_H_
2#define APPARENT_HORIZON_FINDER_TEST_TEMPORARY_DIRECTORY_H_
3
4#include <chrono>
5#include <cstdint>
6#include <filesystem>
7#include <random>
8#include <stdexcept>
9#include <string>
10#include <system_error>
11
13
14// A new, uniquely named directory in the system temp folder, removed with its
15// contents when the object goes out of scope. Tests that write files use it, so
16// that concurrent runs (ctest -j, several checkouts, parallel CI jobs) and
17// leftovers from earlier runs cannot affect each other. A failed assert aborts
18// without running the destructor, which leaves the files for inspection.
20public:
21 explicit TemporaryDirectory(const std::string& prefix) {
22 std::random_device device;
23 std::mt19937_64 generator(
24 (static_cast<std::uint64_t>(device()) << 32)
25 ^ static_cast<std::uint64_t>(
26 std::chrono::steady_clock::now().time_since_epoch().count()));
27 for (int attempt = 0; attempt < 100; ++attempt) {
28 const auto candidate = std::filesystem::temp_directory_path()
29 / (prefix + "-" + std::to_string(generator()));
30 if (std::filesystem::create_directory(candidate)) {
31 _path = candidate;
32 return;
33 }
34 }
35 throw std::runtime_error(
36 "TemporaryDirectory: cannot create a unique directory for " + prefix);
37 }
38
40 std::error_code ignored;
41 std::filesystem::remove_all(_path, ignored);
42 }
43
46
47 const std::filesystem::path& path() const { return _path; }
48
49private:
50 std::filesystem::path _path;
51};
52
53} // namespace exahype2::ccz4::ahf::tests
54
55#endif // APPARENT_HORIZON_FINDER_TEST_TEMPORARY_DIRECTORY_H_
const std::filesystem::path & path() const
TemporaryDirectory(const TemporaryDirectory &)=delete
TemporaryDirectory & operator=(const TemporaryDirectory &)=delete