Skip to content

Commit

Permalink
tmp::path::move creates parent directories (#15)
Browse files Browse the repository at this point in the history
Make tmp::path::move to create the parent directories of the given target if they do not exist
  • Loading branch information
bugdea1er authored Feb 4, 2024
1 parent 3886a89 commit 0798f5a
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
2 changes: 2 additions & 0 deletions include/tmp/path
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions lib/path.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions tests/file_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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) {
Expand Down

0 comments on commit 0798f5a

Please sign in to comment.