libcruft-util/cruft/util/paths_posix.cpp

43 lines
1.1 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 2020, Danny Robson <danny@nerdcruft.net>
*/
#include "paths.hpp"
#include "posix/except.hpp"
#include "debug/assert.hpp"
#include <memory>
#include <wordexp.h>
///////////////////////////////////////////////////////////////////////////////
std::filesystem::path
cruft::paths::temp (void)
{
if (char const *tmpdir = getenv ("TMPDIR"); tmpdir)
return tmpdir;
return "/tmp";
}
///////////////////////////////////////////////////////////////////////////////
std::filesystem::path
cruft::paths::expand (std::filesystem::path const &val)
{
wordexp_t words;
posix::error::try_call (wordexp, val.c_str (), &words, WRDE_NOCMD | WRDE_UNDEF);
std::unique_ptr<wordexp_t, decltype(&wordfree)> cleanup {&words, &wordfree};
if (words.we_wordc != 1)
throw std::runtime_error ("path expansion is not singular");
CHECK_EQ (words.we_offs, 0u);
return words.we_wordv[0];
}