Skip to content

Commit

Permalink
Add TmpFolder for a temporary/auto-removed folder
Browse files Browse the repository at this point in the history
  • Loading branch information
Flamefire committed Jan 30, 2022
1 parent d16fc41 commit 16c51cf
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 5 deletions.
12 changes: 12 additions & 0 deletions libs/common/include/s25util/tmpFile.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,15 @@ class TmpFile

const boost::filesystem::path filePath;
};

/// RAII wrapper for a temporary folder, that is created on construction and deleted on destruction
class TmpFolder
{
boost::filesystem::path filePath;

public:
explicit TmpFolder(boost::filesystem::path parent);
~TmpFolder();

operator boost::filesystem::path() const { return filePath; }
};
35 changes: 30 additions & 5 deletions libs/common/src/tmpFile.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,20 @@
namespace bnw = boost::nowide;
namespace bfs = boost::filesystem;

constexpr unsigned MAX_TRIES = 50;

namespace { /// Creates and opens a temporary binary file with the given extension
/// file must be a closed file stream and open() will be called on it
/// Returns the filename used or an empty string on error
bfs::path createTempFile(bnw::ofstream& file, const std::string& ext /* = ".tmp"*/)
{
static const unsigned MAX_TRIES = 50;

if(file.is_open())
throw std::runtime_error("Passed in an open file handle to createTempFile");

// Temp directory (e.g. /tmp)
bfs::path tmpPath = bfs::temp_directory_path();
unsigned tries = 0;
do

for(unsigned tries = 0; tries < MAX_TRIES; ++tries)
{
// Create a (hopefully) unique filePath
bfs::path filePath = tmpPath / bfs::unique_path();
Expand All @@ -46,7 +46,7 @@ bfs::path createTempFile(bnw::ofstream& file, const std::string& ext /* = ".tmp"
continue;
}
return filePath;
} while(++tries < MAX_TRIES);
}
// Could not find a file :(
return "";
}
Expand Down Expand Up @@ -76,3 +76,28 @@ TmpFile::~TmpFile()
stream.close();
unlinkFile(filePath);
}

TmpFolder::TmpFolder(boost::filesystem::path parent)
{
if(parent.empty())
parent = bfs::temp_directory_path();
for(unsigned tries = 0; tries < MAX_TRIES; ++tries)
{
// Create a (hopefully) unique filePath
filePath = parent / bfs::unique_path();
if(!bfs::exists(filePath))
{
boost::system::error_code ec;
bfs::create_directories(filePath, ec);
if(!ec)
return;
}
}
throw std::runtime_error("Can't create temporary folder");
}

TmpFolder::~TmpFolder()
{
boost::system::error_code ec;
bfs::remove_all(filePath, ec);
}

0 comments on commit 16c51cf

Please sign in to comment.