libcruft-util/fs/scoped.hpp

53 lines
1.7 KiB
C++

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2022, Danny Robson <danny@nerdcruft.net>
*/
#include <optional>
#include <filesystem>
///////////////////////////////////////////////////////////////////////////////
namespace cruft::fs {
/// Holds a path and deletes the path (and it any contents if it's a
/// directory) at destruction.
class scoped_path {
public:
explicit scoped_path (std::filesystem::path const&);
explicit scoped_path (std::filesystem::path &&);
scoped_path (scoped_path const&) = delete;
scoped_path& operator= (scoped_path const&) = delete;
scoped_path (scoped_path&&) noexcept = default;
scoped_path& operator= (scoped_path&&) noexcept = default;
~scoped_path ();
std::filesystem::path const& get (void) const&;
std::filesystem::path release (void);
void reset (void);
private:
std::optional<std::filesystem::path> m_path;
};
///------------------------------------------------------------------------
/// Holds the path to a directory that will be deleted (along with all
/// contents) when the object goes out of scope.
class scoped_dir : public scoped_path {
public:
explicit scoped_dir (std::filesystem::path const&);
explicit scoped_dir (std::filesystem::path &&);
using scoped_path::scoped_path;
std::filesystem::path const& operator* () const&;
std::filesystem::path const* operator-> () const&;
};
}