-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDirectory.mpp
More file actions
75 lines (67 loc) · 2.45 KB
/
Copy pathDirectory.mpp
File metadata and controls
75 lines (67 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
export module CppUtils.FileSystem.Directory;
import std;
import CppUtils.Type.Concept;
export namespace CppUtils::FileSystem
{
inline auto forDirectories(
const std::filesystem::path& directoryPath,
auto&& function,
bool recursively = false) -> void
{
if (not std::filesystem::exists(directoryPath) or
not std::filesystem::is_directory(directoryPath))
return;
if (recursively)
{
for (const auto& directoryEntry : std::filesystem::recursive_directory_iterator(directoryPath))
if (const auto& path = directoryEntry.path(); std::filesystem::is_directory(path))
function(path);
}
else
for (const auto& directoryEntry : std::filesystem::directory_iterator(directoryPath))
if (const auto& path = directoryEntry.path(); std::filesystem::is_directory(path))
function(path);
}
class TemporaryDirectory final
{
public:
inline explicit TemporaryDirectory(std::string_view directoryName = "temp")
{
static auto temporaryDirectoryIndex = std::atomic_size_t{0};
auto temporaryFileIndex = temporaryDirectoryIndex.fetch_add(1);
do
{
m_tempDirectory = std::filesystem::temp_directory_path() / std::format("{}{}", directoryName, temporaryFileIndex++);
}
while (std::filesystem::exists(m_tempDirectory));
std::filesystem::create_directory(m_tempDirectory);
m_tempDirectory = std::filesystem::canonical(m_tempDirectory);
}
inline explicit TemporaryDirectory(std::invocable<std::filesystem::path> auto&& function, [[maybe_unused]] auto&&... args):
TemporaryDirectory{}
{
static_assert(not Type::HasReturnValue<decltype(function)>);
function(m_tempDirectory, std::forward<decltype(args)>(args)...);
}
inline TemporaryDirectory(std::string_view directoryName, std::invocable<std::filesystem::path> auto&& function, [[maybe_unused]] auto&&... args):
TemporaryDirectory{directoryName}
{
static_assert(not Type::HasReturnValue<decltype(function)>);
function(m_tempDirectory, std::forward<decltype(args)>(args)...);
}
inline ~TemporaryDirectory()
{
auto errorCode = std::error_code{};
std::filesystem::remove_all(m_tempDirectory, errorCode);
}
inline auto execute(auto&& function, auto&&... args) -> decltype(auto)
{
if constexpr (Type::HasReturnValue<decltype(function)>)
return function(m_tempDirectory, std::forward<decltype(args)>(args)...);
else
function(m_tempDirectory, std::forward<decltype(args)>(args)...);
}
private:
std::filesystem::path m_tempDirectory;
};
}