From e82785d6b5da237931288255481143f7b1430e51 Mon Sep 17 00:00:00 2001 From: Maksim Denisov Date: Mon, 17 Feb 2025 14:30:30 +0100 Subject: TmpDir: Create temporary files ... and keep parent directories alive while nested directories exist. --- src/utils/cpp/tmp_dir.cpp | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) (limited to 'src/utils/cpp/tmp_dir.cpp') diff --git a/src/utils/cpp/tmp_dir.cpp b/src/utils/cpp/tmp_dir.cpp index 88cc0f98..8d6e0724 100644 --- a/src/utils/cpp/tmp_dir.cpp +++ b/src/utils/cpp/tmp_dir.cpp @@ -21,7 +21,6 @@ #endif #include -#include #include #include @@ -41,6 +40,28 @@ auto TmpDir::CreateNestedDirectory(TmpDir::Ptr const& parent) noexcept return CreateImpl(parent, parent->GetPath()); } +auto TmpDir::CreateFile(TmpDir::Ptr const& parent, + std::string const& file_name) noexcept -> TmpFile::Ptr { + // Create a new tmp directory to guarantee uniqueness: + auto temp_dir = CreateNestedDirectory(parent); + if (temp_dir == nullptr) { + return nullptr; + } + + try { + auto file_path = std::filesystem::weakly_canonical( + std::filesystem::absolute(temp_dir->GetPath() / file_name)); + if (not FileSystemManager::CreateFile(file_path)) { + return nullptr; + } + + return std::shared_ptr{ + new TmpFile(std::move(temp_dir), std::move(file_path))}; + } catch (...) { + return nullptr; + } +} + auto TmpDir::CreateImpl(TmpDir::Ptr parent, std::filesystem::path const& path) noexcept -> Ptr { static constexpr std::string_view kDirTemplate = "tmp.XXXXXX"; -- cgit v1.2.3