libcruft-util/fs/scoped.cpp

101 lines
2.4 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 "./scoped.hpp"
#include "./tmp.hpp"
#include <cruft/util/debug/assert.hpp>
using cruft::fs::scoped_dir;
using cruft::fs::scoped_path;
///////////////////////////////////////////////////////////////////////////////
scoped_path::scoped_path (std::filesystem::path &&_path)
: m_path (std::move (_path))
{
CHECK (std::filesystem::exists (*m_path));
}
//-----------------------------------------------------------------------------
scoped_path::scoped_path (std::filesystem::path const &_path)
: scoped_path (std::filesystem::path (_path))
{ ; }
//-----------------------------------------------------------------------------
std::filesystem::path const &
scoped_path::operator* () const &
{
return get ();
}
//-----------------------------------------------------------------------------
std::filesystem::path const*
scoped_path::operator-> () const &
{
return &get();
}
//-----------------------------------------------------------------------------
std::filesystem::path const&
scoped_path::get () const&
{
return *m_path;
}
//-----------------------------------------------------------------------------
std::filesystem::path
scoped_path::release ()
{
auto res = std::move (*m_path);
m_path.reset ();
return res;
}
//-----------------------------------------------------------------------------
void
scoped_path::reset (void)
{
return m_path.reset ();
}
//-----------------------------------------------------------------------------
scoped_path::~scoped_path ()
{
if (m_path)
std::filesystem::remove_all (*m_path);
}
///////////////////////////////////////////////////////////////////////////////
scoped_dir::scoped_dir (std::filesystem::path const &_path)
: scoped_dir (std::filesystem::path (_path))
{}
//-----------------------------------------------------------------------------
scoped_dir::scoped_dir (std::filesystem::path &&_path)
: scoped_path (std::move (_path))
{
CHECK (std::filesystem::is_directory (get ()));
}
///////////////////////////////////////////////////////////////////////////////
cruft::fs::scoped_dir
cruft::fs::scoped_tmpdir ()
{
return scoped_dir (cruft::fs::mktmpdir ());
}