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

101 lines
2.4 KiB
C++
Raw 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 "./scoped.hpp"
#include "./tmp.hpp"
2022-01-19 12:21:30 +11:00
#include <cruft/util/debug/assert.hpp>
using cruft::fs::scoped_dir;
2022-06-01 14:55:59 +10:00
using cruft::fs::scoped_path;
2022-01-19 12:21:30 +11:00
///////////////////////////////////////////////////////////////////////////////
2022-06-01 14:55:59 +10:00
scoped_path::scoped_path (std::filesystem::path &&_path)
: m_path (std::move (_path))
{
CHECK (std::filesystem::exists (*m_path));
}
2022-01-19 12:21:30 +11:00
//-----------------------------------------------------------------------------
2022-06-01 14:55:59 +10:00
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();
}
2022-06-01 14:55:59 +10:00
//-----------------------------------------------------------------------------
std::filesystem::path const&
scoped_path::get () const&
2022-01-19 12:21:30 +11:00
{
2022-06-01 14:55:59 +10:00
return *m_path;
2022-01-19 12:21:30 +11:00
}
2022-06-01 14:55:59 +10:00
//-----------------------------------------------------------------------------
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 ()
2022-01-19 12:21:30 +11:00
{
if (m_path)
std::filesystem::remove_all (*m_path);
}
///////////////////////////////////////////////////////////////////////////////
2022-06-01 14:55:59 +10:00
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 ());
}