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

75 lines
1.9 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 2023, Danny Robson <danny@nerdcruft.net>
*/
#include "./tmp.hpp"
#include "../paths.hpp"
#include "../posix/except.hpp"
#include <io.h>
#include <direct.h>
///////////////////////////////////////////////////////////////////////////////
static std::filesystem::path
_temp_path_at (std::filesystem::path const &root)
{
// The pattern suffix we'll append to the temp directory.
//
// * We might as well append the package name for clarity
// * The libc call REQUIRES the string end with "XXXXXX"
char const SUFFIX[] = "/" PACKAGE_NAME "-XXXXXX";
std::string path;
path.reserve (root.string ().size () + sizeof (SUFFIX));
path = root.string ();
path += SUFFIX;
if (auto const err = _mktemp_s (path.data (), path.size ()); err)
throw cruft::posix::error (err);
return path;
}
///////////////////////////////////////////////////////////////////////////////
std::filesystem::path
cruft::fs::mktempfile (std::filesystem::path const &dir)
{
auto pattern = (dir / PACKAGE_NAME "-XXXXXX").string ();
auto const fd = mkstemp (pattern.data ());
if (fd < 0)
cruft::posix::error::throw_code ();
cruft::posix::error::try_call(::close, fd);
return pattern;
}
///////////////////////////////////////////////////////////////////////////////
std::filesystem::path
cruft::fs::mktmpdir (void)
{
static constexpr int RETRIES = 10;
auto const root = cruft::paths::temp ();
for (int i = 0; i < RETRIES; ++i) {
auto const path = _temp_path_at (root);
if (_mkdir (path.string ().c_str ()))
continue;
return path;
}
throw std::runtime_error ("Unable to create tmpdir");
}