Skip to content

Commit

Permalink
Add tmp::path::move
Browse files Browse the repository at this point in the history
  • Loading branch information
bugdea1er committed Feb 3, 2024
1 parent 6e9a1f1 commit 6e3452d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
5 changes: 5 additions & 0 deletions include/tmp/path
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ public:
/// @returns The managed path
std::filesystem::path release() noexcept;

/// Moves the managed path recursively, releasing the ownership
/// @param target 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& target);

/// Deletes the managed path recursively if it is not empty
virtual ~path() noexcept;

Expand Down
17 changes: 17 additions & 0 deletions lib/path.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
namespace fs = std::filesystem;

namespace {
const fs::copy_options copy_options = fs::copy_options::recursive
| fs::copy_options::overwrite_existing;

/// Deletes the given path recursively, ignoring any errors
/// @param path The path of the directory to remove
Expand Down Expand Up @@ -50,6 +52,21 @@ fs::path path::release() noexcept {
return path;
}

void path::move(const fs::path& target) {
std::error_code ec;
fs::rename(*this, target, ec);
if (ec == std::errc::cross_device_link) {
fs::copy(*this, target, copy_options, ec);
}

if (!ec) {
throw fs::filesystem_error("Cannot move temporary resource", ec);
}

remove(*this);
release();
}

fs::path path::make_pattern(std::string_view prefix) {
fs::path parent = fs::temp_directory_path() / prefix;
fs::create_directories(parent);
Expand Down

0 comments on commit 6e3452d

Please sign in to comment.