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 4, 2024
1 parent 6e9a1f1 commit 4177cf8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
8 changes: 7 additions & 1 deletion include/tmp/path
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ public:
/// @returns The managed path
std::filesystem::path release() noexcept;

/// Moves the managed path recursively to a given target, releasing
/// ownership of the managed path
/// @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);

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

Expand All @@ -48,7 +54,7 @@ public:
/// The parent of the resulting path is created when this function is called
/// @param prefix A prefix to be used in the path pattern
/// @returns A path pattern for the unique temporary path
/// @throws std::filesystem::filesystem_error if failed to create the parent
/// @throws std::filesystem::filesystem_error if cannot create the parent
static std::filesystem::path make_pattern(std::string_view prefix);

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

namespace {

/// Options for recursive overwriting coping
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
void remove(const tmp::path& path) noexcept {
Expand Down Expand Up @@ -50,6 +54,21 @@ fs::path path::release() noexcept {
return path;
}

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

if (ec) {
throw fs::filesystem_error("Cannot move temporary resource", to, 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 4177cf8

Please sign in to comment.