From 0798f5a5ecabbf180ee9edfe042593301f2d8826 Mon Sep 17 00:00:00 2001 From: Ilya Andreev Date: Sun, 4 Feb 2024 23:16:01 +0300 Subject: [PATCH] tmp::path::move creates parent directories (#15) Make tmp::path::move to create the parent directories of the given target if they do not exist --- README.md | 2 +- include/tmp/path | 2 ++ lib/path.cpp | 2 ++ tests/file_test.cpp | 4 ++-- 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 86ab7a6..0529a87 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ auto tmpfile = tmp::file("org.example.product"); tmpfile.write(data); if (validate_metadata(tmpfile)) { - fs::copy(tmpfile, storage); + tmpfile.move(storage / "new_file"); } else { throw InvalidRequestError(); } diff --git a/include/tmp/path b/include/tmp/path index dc1f84f..4b8db24 100644 --- a/include/tmp/path +++ b/include/tmp/path @@ -33,6 +33,8 @@ public: /// Moves the managed path recursively to a given target, releasing /// ownership of the managed path + /// + /// The parent of the target path is created when this function is called /// @param to A path to the target file or directory /// @throws std::filesystem::filesystem_error if cannot move the owned path void move(const std::filesystem::path& to); diff --git a/lib/path.cpp b/lib/path.cpp index 06c4dcb..17eeaa8 100644 --- a/lib/path.cpp +++ b/lib/path.cpp @@ -55,6 +55,8 @@ fs::path path::release() noexcept { } void path::move(const fs::path& to) { + fs::create_directories(to.parent_path()); + std::error_code ec; fs::rename(*this, to, ec); if (ec == std::errc::cross_device_link) { diff --git a/tests/file_test.cpp b/tests/file_test.cpp index 6ff1150..16142aa 100644 --- a/tests/file_test.cpp +++ b/tests/file_test.cpp @@ -53,7 +53,7 @@ TEST(FileTest, Release) { TEST(FileTest, MoveFile) { auto path = fs::path(); - auto to = fs::temp_directory_path() / PREFIX / "moved"; + auto to = fs::temp_directory_path() / PREFIX / "non-existing" / "parent"; { auto tmpfile = tmp::file(PREFIX); path = tmpfile; @@ -63,7 +63,7 @@ TEST(FileTest, MoveFile) { ASSERT_FALSE(fs::exists(path)); ASSERT_TRUE(fs::exists(to)); - fs::remove_all(to); + fs::remove_all(fs::temp_directory_path() / PREFIX / "non-existing"); } TEST(FileTest, MoveConstruction) {