libcruft-util/cruft/util/fs/scoped.hpp

57 lines
1.8 KiB
C++
Raw Permalink Normal View History

2022-01-19 12:21:30 +11:00
/*
* 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 {
2022-06-01 14:55:59 +10:00
/// 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& operator* (void) const&;
std::filesystem::path const* operator-> (void) const&;
2022-06-01 14:55:59 +10:00
std::filesystem::path const& get (void) const&;
std::filesystem::path release (void);
void reset (void);
private:
std::optional<std::filesystem::path> m_path;
};
2022-01-19 12:21:30 +11:00
///------------------------------------------------------------------------
/// Holds the path to a directory that will be deleted (along with all
/// contents) when the object goes out of scope.
2022-06-01 14:55:59 +10:00
class scoped_dir : public scoped_path {
2022-01-19 12:21:30 +11:00
public:
explicit scoped_dir (std::filesystem::path const&);
explicit scoped_dir (std::filesystem::path &&);
2022-06-01 14:55:59 +10:00
using scoped_path::scoped_path;
2022-01-19 12:21:30 +11:00
};
/// A convenience function equivalent to `scoped_dir(maketmpdir())`
scoped_dir scoped_tmpdir (void);
2022-01-19 12:21:30 +11:00
}