1
1
Fork 0
mirror of https://github.com/NixOS/nix.git synced 2025-11-28 13:11:00 +01:00

Merge pull request #14652 from vinayakankugoyal/path

Replace Path with std::filesystem::path in libfetchers.
This commit is contained in:
John Ericson 2025-11-26 17:07:43 +00:00 committed by GitHub
commit 3c2d5a1bdc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 73 additions and 71 deletions

View file

@ -18,13 +18,13 @@ TEST_F(nix_api_expr_test, nix_eval_state_lookup_path)
{ {
auto tmpDir = nix::createTempDir(); auto tmpDir = nix::createTempDir();
auto delTmpDir = std::make_unique<nix::AutoDelete>(tmpDir, true); auto delTmpDir = std::make_unique<nix::AutoDelete>(tmpDir, true);
auto nixpkgs = tmpDir + "/pkgs"; auto nixpkgs = tmpDir / "pkgs";
auto nixos = tmpDir + "/cfg"; auto nixos = tmpDir / "cfg";
std::filesystem::create_directories(nixpkgs); std::filesystem::create_directories(nixpkgs);
std::filesystem::create_directories(nixos); std::filesystem::create_directories(nixos);
std::string nixpkgsEntry = "nixpkgs=" + nixpkgs; std::string nixpkgsEntry = "nixpkgs=" + nixpkgs.string();
std::string nixosEntry = "nixos-config=" + nixos; std::string nixosEntry = "nixos-config=" + nixos.string();
const char * lookupPath[] = {nixpkgsEntry.c_str(), nixosEntry.c_str(), nullptr}; const char * lookupPath[] = {nixpkgsEntry.c_str(), nixosEntry.c_str(), nullptr};
auto builder = nix_eval_state_builder_new(ctx, store); auto builder = nix_eval_state_builder_new(ctx, store);

View file

@ -384,7 +384,7 @@ path_start
std::string_view($1.p, $1.l) std::string_view($1.p, $1.l)
); );
} }
Path path(getHome() + std::string($1.p + 1, $1.l - 1)); Path path(getHome().string() + std::string($1.p + 1, $1.l - 1));
$$ = state->exprs.add<ExprPath>(state->exprs.alloc, ref<SourceAccessor>(state->rootFS), path); $$ = state->exprs.add<ExprPath>(state->exprs.alloc, ref<SourceAccessor>(state->rootFS), path);
} }
; ;

View file

@ -268,10 +268,10 @@ void Fetch::fetch(
return; return;
} }
Path cacheDir = getCacheDir() + "/git-lfs"; std::filesystem::path cacheDir = getCacheDir() / "git-lfs";
std::string key = hashString(HashAlgorithm::SHA256, pointerFilePath.rel()).to_string(HashFormat::Base16, false) std::string key = hashString(HashAlgorithm::SHA256, pointerFilePath.rel()).to_string(HashFormat::Base16, false)
+ "/" + pointer->oid; + "/" + pointer->oid;
Path cachePath = cacheDir + "/" + key; std::filesystem::path cachePath = cacheDir / key;
if (pathExists(cachePath)) { if (pathExists(cachePath)) {
debug("using cache entry %s -> %s", key, cachePath); debug("using cache entry %s -> %s", key, cachePath);
sink(readFile(cachePath)); sink(readFile(cachePath));
@ -302,8 +302,8 @@ void Fetch::fetch(
downloadToSink(ourl, authHeader, sink, sha256, size); downloadToSink(ourl, authHeader, sink, sha256, size);
debug("creating cache entry %s -> %s", key, cachePath); debug("creating cache entry %s -> %s", key, cachePath);
if (!pathExists(dirOf(cachePath))) if (!pathExists(cachePath.parent_path()))
createDirs(dirOf(cachePath)); createDirs(cachePath.parent_path());
writeFile(cachePath, sink.s); writeFile(cachePath, sink.s);
debug("%s fetched with git-lfs", pointerFilePath); debug("%s fetched with git-lfs", pointerFilePath);

View file

@ -206,7 +206,7 @@ static void initRepoAtomically(std::filesystem::path & path, bool bare)
if (pathExists(path.string())) if (pathExists(path.string()))
return; return;
Path tmpDir = createTempDir(os_string_to_string(PathViewNG{std::filesystem::path(path).parent_path()})); std::filesystem::path tmpDir = createTempDir(path.parent_path());
AutoDelete delTmpDir(tmpDir, true); AutoDelete delTmpDir(tmpDir, true);
Repository tmpRepo; Repository tmpRepo;

View file

@ -42,10 +42,10 @@ bool isCacheFileWithinTtl(time_t now, const struct stat & st)
return st.st_mtime + static_cast<time_t>(settings.tarballTtl) > now; return st.st_mtime + static_cast<time_t>(settings.tarballTtl) > now;
} }
Path getCachePath(std::string_view key, bool shallow) std::filesystem::path getCachePath(std::string_view key, bool shallow)
{ {
return getCacheDir() + "/gitv3/" + hashString(HashAlgorithm::SHA256, key).to_string(HashFormat::Nix32, false) return getCacheDir() / "gitv3"
+ (shallow ? "-shallow" : ""); / (hashString(HashAlgorithm::SHA256, key).to_string(HashFormat::Nix32, false) + (shallow ? "-shallow" : ""));
} }
// Returns the name of the HEAD branch. // Returns the name of the HEAD branch.
@ -55,7 +55,7 @@ Path getCachePath(std::string_view key, bool shallow)
// //
// ref: refs/heads/main HEAD // ref: refs/heads/main HEAD
// ... // ...
std::optional<std::string> readHead(const Path & path) std::optional<std::string> readHead(const std::filesystem::path & path)
{ {
auto [status, output] = runProgram( auto [status, output] = runProgram(
RunOptions{ RunOptions{
@ -86,7 +86,7 @@ std::optional<std::string> readHead(const Path & path)
// Persist the HEAD ref from the remote repo in the local cached repo. // Persist the HEAD ref from the remote repo in the local cached repo.
bool storeCachedHead(const std::string & actualUrl, bool shallow, const std::string & headRef) bool storeCachedHead(const std::string & actualUrl, bool shallow, const std::string & headRef)
{ {
Path cacheDir = getCachePath(actualUrl, shallow); std::filesystem::path cacheDir = getCachePath(actualUrl, shallow);
try { try {
runProgram("git", true, {"-C", cacheDir, "--git-dir", ".", "symbolic-ref", "--", "HEAD", headRef}); runProgram("git", true, {"-C", cacheDir, "--git-dir", ".", "symbolic-ref", "--", "HEAD", headRef});
} catch (ExecError & e) { } catch (ExecError & e) {
@ -109,8 +109,8 @@ std::optional<std::string> readHeadCached(const std::string & actualUrl, bool sh
{ {
// Create a cache path to store the branch of the HEAD ref. Append something // Create a cache path to store the branch of the HEAD ref. Append something
// in front of the URL to prevent collision with the repository itself. // in front of the URL to prevent collision with the repository itself.
Path cacheDir = getCachePath(actualUrl, shallow); std::filesystem::path cacheDir = getCachePath(actualUrl, shallow);
Path headRefFile = cacheDir + "/HEAD"; std::filesystem::path headRefFile = cacheDir / "HEAD";
time_t now = time(0); time_t now = time(0);
struct stat st; struct stat st;

View file

@ -39,7 +39,7 @@ struct Registry
static std::shared_ptr<Registry> read(const Settings & settings, const SourcePath & path, RegistryType type); static std::shared_ptr<Registry> read(const Settings & settings, const SourcePath & path, RegistryType type);
void write(const Path & path); void write(const std::filesystem::path & path);
void add(const Input & from, const Input & to, const Attrs & extraAttrs); void add(const Input & from, const Input & to, const Attrs & extraAttrs);
@ -50,9 +50,9 @@ typedef std::vector<std::shared_ptr<Registry>> Registries;
std::shared_ptr<Registry> getUserRegistry(const Settings & settings); std::shared_ptr<Registry> getUserRegistry(const Settings & settings);
std::shared_ptr<Registry> getCustomRegistry(const Settings & settings, const Path & p); std::shared_ptr<Registry> getCustomRegistry(const Settings & settings, const std::filesystem::path & p);
Path getUserRegistryPath(); std::filesystem::path getUserRegistryPath();
Registries getRegistries(const Settings & settings, Store & store); Registries getRegistries(const Settings & settings, Store & store);

View file

@ -213,11 +213,11 @@ struct MercurialInputScheme : InputScheme
runHg({"status", "-R", actualUrl, "--clean", "--modified", "--added", "--no-status", "--print0"}), runHg({"status", "-R", actualUrl, "--clean", "--modified", "--added", "--no-status", "--print0"}),
"\0"s); "\0"s);
Path actualPath(absPath(actualUrl)); std::filesystem::path actualPath(absPath(actualUrl));
PathFilter filter = [&](const Path & p) -> bool { PathFilter filter = [&](const Path & p) -> bool {
assert(hasPrefix(p, actualPath)); assert(hasPrefix(p, actualPath.string()));
std::string file(p, actualPath.size() + 1); std::string file(p, actualPath.string().size() + 1);
auto st = lstat(p); auto st = lstat(p);
@ -232,7 +232,7 @@ struct MercurialInputScheme : InputScheme
auto storePath = store.addToStore( auto storePath = store.addToStore(
input.getName(), input.getName(),
{getFSSourceAccessor(), CanonPath(actualPath)}, {getFSSourceAccessor(), CanonPath(actualPath.string())},
ContentAddressMethod::Raw::NixArchive, ContentAddressMethod::Raw::NixArchive,
HashAlgorithm::SHA256, HashAlgorithm::SHA256,
{}, {},
@ -275,10 +275,8 @@ struct MercurialInputScheme : InputScheme
return makeResult(res->value, res->storePath); return makeResult(res->value, res->storePath);
} }
Path cacheDir = std::filesystem::path cacheDir =
fmt("%s/hg/%s", getCacheDir() / "hg" / hashString(HashAlgorithm::SHA256, actualUrl).to_string(HashFormat::Nix32, false);
getCacheDir(),
hashString(HashAlgorithm::SHA256, actualUrl).to_string(HashFormat::Nix32, false));
/* If this is a commit hash that we already have, we don't /* If this is a commit hash that we already have, we don't
have to pull again. */ have to pull again. */
@ -292,7 +290,7 @@ struct MercurialInputScheme : InputScheme
try { try {
runHg({"pull", "-R", cacheDir, "--", actualUrl}); runHg({"pull", "-R", cacheDir, "--", actualUrl});
} catch (ExecError & e) { } catch (ExecError & e) {
auto transJournal = cacheDir + "/.hg/store/journal"; auto transJournal = cacheDir / ".hg" / "store" / "journal";
/* hg throws "abandoned transaction" error only if this file exists */ /* hg throws "abandoned transaction" error only if this file exists */
if (pathExists(transJournal)) { if (pathExists(transJournal)) {
runHg({"recover", "-R", cacheDir}); runHg({"recover", "-R", cacheDir});
@ -302,7 +300,7 @@ struct MercurialInputScheme : InputScheme
} }
} }
} else { } else {
createDirs(dirOf(cacheDir)); createDirs(dirOf(cacheDir.string()));
runHg({"clone", "--noupdate", "--", actualUrl, cacheDir}); runHg({"clone", "--noupdate", "--", actualUrl, cacheDir});
} }
} }
@ -328,14 +326,14 @@ struct MercurialInputScheme : InputScheme
if (auto res = settings.getCache()->lookupStorePath(revInfoKey(rev), store)) if (auto res = settings.getCache()->lookupStorePath(revInfoKey(rev), store))
return makeResult(res->value, res->storePath); return makeResult(res->value, res->storePath);
Path tmpDir = createTempDir(); std::filesystem::path tmpDir = createTempDir();
AutoDelete delTmpDir(tmpDir, true); AutoDelete delTmpDir(tmpDir, true);
runHg({"archive", "-R", cacheDir, "-r", rev.gitRev(), tmpDir}); runHg({"archive", "-R", cacheDir, "-r", rev.gitRev(), tmpDir});
deletePath(tmpDir + "/.hg_archival.txt"); deletePath(tmpDir / ".hg_archival.txt");
auto storePath = store.addToStore(name, {getFSSourceAccessor(), CanonPath(tmpDir)}); auto storePath = store.addToStore(name, {getFSSourceAccessor(), CanonPath(tmpDir.string())});
Attrs infoAttrs({ Attrs infoAttrs({
{"revCount", (uint64_t) revCount}, {"revCount", (uint64_t) revCount},

View file

@ -56,7 +56,7 @@ std::shared_ptr<Registry> Registry::read(const Settings & settings, const Source
return registry; return registry;
} }
void Registry::write(const Path & path) void Registry::write(const std::filesystem::path & path)
{ {
nlohmann::json arr; nlohmann::json arr;
for (auto & entry : entries) { for (auto & entry : entries) {
@ -74,7 +74,7 @@ void Registry::write(const Path & path)
json["version"] = 2; json["version"] = 2;
json["flakes"] = std::move(arr); json["flakes"] = std::move(arr);
createDirs(dirOf(path)); createDirs(path.parent_path());
writeFile(path, json.dump(2)); writeFile(path, json.dump(2));
} }
@ -90,38 +90,38 @@ void Registry::remove(const Input & input)
entries.end()); entries.end());
} }
static Path getSystemRegistryPath() static std::filesystem::path getSystemRegistryPath()
{ {
return settings.nixConfDir + "/registry.json"; return settings.nixConfDir / "registry.json";
} }
static std::shared_ptr<Registry> getSystemRegistry(const Settings & settings) static std::shared_ptr<Registry> getSystemRegistry(const Settings & settings)
{ {
static auto systemRegistry = Registry::read( static auto systemRegistry = Registry::read(
settings, settings,
SourcePath{getFSSourceAccessor(), CanonPath{getSystemRegistryPath()}}.resolveSymlinks(), SourcePath{getFSSourceAccessor(), CanonPath{getSystemRegistryPath().string()}}.resolveSymlinks(),
Registry::System); Registry::System);
return systemRegistry; return systemRegistry;
} }
Path getUserRegistryPath() std::filesystem::path getUserRegistryPath()
{ {
return getConfigDir() + "/registry.json"; return getConfigDir() / "registry.json";
} }
std::shared_ptr<Registry> getUserRegistry(const Settings & settings) std::shared_ptr<Registry> getUserRegistry(const Settings & settings)
{ {
static auto userRegistry = Registry::read( static auto userRegistry = Registry::read(
settings, settings,
SourcePath{getFSSourceAccessor(), CanonPath{getUserRegistryPath()}}.resolveSymlinks(), SourcePath{getFSSourceAccessor(), CanonPath{getUserRegistryPath().string()}}.resolveSymlinks(),
Registry::User); Registry::User);
return userRegistry; return userRegistry;
} }
std::shared_ptr<Registry> getCustomRegistry(const Settings & settings, const Path & p) std::shared_ptr<Registry> getCustomRegistry(const Settings & settings, const std::filesystem::path & p)
{ {
static auto customRegistry = static auto customRegistry = Registry::read(
Registry::read(settings, SourcePath{getFSSourceAccessor(), CanonPath{p}}.resolveSymlinks(), Registry::Custom); settings, SourcePath{getFSSourceAccessor(), CanonPath{p.string()}}.resolveSymlinks(), Registry::Custom);
return customRegistry; return customRegistry;
} }

View file

@ -86,7 +86,7 @@ TEST_F(nix_api_store_test, nix_api_load_flake)
auto tmpDir = nix::createTempDir(); auto tmpDir = nix::createTempDir();
nix::AutoDelete delTmpDir(tmpDir, true); nix::AutoDelete delTmpDir(tmpDir, true);
nix::writeFile(tmpDir + "/flake.nix", R"( nix::writeFile(tmpDir / "flake.nix", R"(
{ {
outputs = { ... }: { outputs = { ... }: {
hello = "potato"; hello = "potato";
@ -121,7 +121,8 @@ TEST_F(nix_api_store_test, nix_api_load_flake)
assert_ctx_ok(); assert_ctx_ok();
ASSERT_NE(nullptr, parseFlags); ASSERT_NE(nullptr, parseFlags);
auto r0 = nix_flake_reference_parse_flags_set_base_directory(ctx, parseFlags, tmpDir.c_str(), tmpDir.size()); auto r0 =
nix_flake_reference_parse_flags_set_base_directory(ctx, parseFlags, tmpDir.c_str(), tmpDir.string().size());
assert_ctx_ok(); assert_ctx_ok();
ASSERT_EQ(NIX_OK, r0); ASSERT_EQ(NIX_OK, r0);
@ -177,8 +178,8 @@ TEST_F(nix_api_store_test, nix_api_load_flake_with_flags)
auto tmpDir = nix::createTempDir(); auto tmpDir = nix::createTempDir();
nix::AutoDelete delTmpDir(tmpDir, true); nix::AutoDelete delTmpDir(tmpDir, true);
nix::createDirs(tmpDir + "/b"); nix::createDirs(tmpDir / "b");
nix::writeFile(tmpDir + "/b/flake.nix", R"( nix::writeFile(tmpDir / "b" / "flake.nix", R"(
{ {
outputs = { ... }: { outputs = { ... }: {
hello = "BOB"; hello = "BOB";
@ -186,18 +187,18 @@ TEST_F(nix_api_store_test, nix_api_load_flake_with_flags)
} }
)"); )");
nix::createDirs(tmpDir + "/a"); nix::createDirs(tmpDir / "a");
nix::writeFile(tmpDir + "/a/flake.nix", R"( nix::writeFile(tmpDir / "a" / "flake.nix", R"(
{ {
inputs.b.url = ")" + tmpDir + R"(/b"; inputs.b.url = ")" + tmpDir.string() + R"(/b";
outputs = { b, ... }: { outputs = { b, ... }: {
hello = b.hello; hello = b.hello;
}; };
} }
)"); )");
nix::createDirs(tmpDir + "/c"); nix::createDirs(tmpDir / "c");
nix::writeFile(tmpDir + "/c/flake.nix", R"( nix::writeFile(tmpDir / "c" / "flake.nix", R"(
{ {
outputs = { ... }: { outputs = { ... }: {
hello = "Claire"; hello = "Claire";
@ -230,7 +231,8 @@ TEST_F(nix_api_store_test, nix_api_load_flake_with_flags)
assert_ctx_ok(); assert_ctx_ok();
ASSERT_NE(nullptr, parseFlags); ASSERT_NE(nullptr, parseFlags);
auto r0 = nix_flake_reference_parse_flags_set_base_directory(ctx, parseFlags, tmpDir.c_str(), tmpDir.size()); auto r0 =
nix_flake_reference_parse_flags_set_base_directory(ctx, parseFlags, tmpDir.c_str(), tmpDir.string().size());
assert_ctx_ok(); assert_ctx_ok();
ASSERT_EQ(NIX_OK, r0); ASSERT_EQ(NIX_OK, r0);

View file

@ -212,9 +212,9 @@ TEST_F(nix_api_store_test, nix_store_real_path)
TEST_F(nix_api_util_context, nix_store_real_path_relocated) TEST_F(nix_api_util_context, nix_store_real_path_relocated)
{ {
auto tmp = nix::createTempDir(); auto tmp = nix::createTempDir();
std::string storeRoot = tmp + "/store"; std::string storeRoot = tmp / "store";
std::string stateDir = tmp + "/state"; std::string stateDir = tmp / "state";
std::string logDir = tmp + "/log"; std::string logDir = tmp / "log";
const char * rootkv[] = {"root", storeRoot.c_str()}; const char * rootkv[] = {"root", storeRoot.c_str()};
const char * statekv[] = {"state", stateDir.c_str()}; const char * statekv[] = {"state", stateDir.c_str()};
const char * logkv[] = {"log", logDir.c_str()}; const char * logkv[] = {"log", logDir.c_str()};
@ -250,7 +250,8 @@ TEST_F(nix_api_util_context, nix_store_real_path_relocated)
TEST_F(nix_api_util_context, nix_store_real_path_binary_cache) TEST_F(nix_api_util_context, nix_store_real_path_binary_cache)
{ {
Store * store = nix_store_open(ctx, nix::fmt("file://%s/binary-cache", nix::createTempDir()).c_str(), nullptr); Store * store =
nix_store_open(ctx, nix::fmt("file://%s/binary-cache", nix::createTempDir().string()).c_str(), nullptr);
assert_ctx_ok(); assert_ctx_ok();
ASSERT_NE(store, nullptr); ASSERT_NE(store, nullptr);

View file

@ -486,7 +486,7 @@ void initLibStore(bool loadConfig)
/* On macOS, don't use the per-session TMPDIR (as set e.g. by /* On macOS, don't use the per-session TMPDIR (as set e.g. by
sshd). This breaks build users because they don't have access sshd). This breaks build users because they don't have access
to the TMPDIR, in particular in nix-store --serve. */ to the TMPDIR, in particular in nix-store --serve. */
if (hasPrefix(defaultTempDir(), "/var/folders/")) if (hasPrefix(defaultTempDir().string(), "/var/folders/"))
unsetenv("TMPDIR"); unsetenv("TMPDIR");
#endif #endif

View file

@ -101,7 +101,7 @@ public:
/** /**
* The directory where system configuration files are stored. * The directory where system configuration files are stored.
*/ */
Path nixConfDir; std::filesystem::path nixConfDir;
/** /**
* A list of user configuration files to load. * A list of user configuration files to load.
@ -292,7 +292,7 @@ public:
Setting<std::string> builders{ Setting<std::string> builders{
this, this,
"@" + nixConfDir + "/machines", "@" + nixConfDir.string() + "/machines",
"builders", "builders",
R"( R"(
A semicolon- or newline-separated list of build machines. A semicolon- or newline-separated list of build machines.

View file

@ -1332,7 +1332,7 @@ std::pair<std::filesystem::path, AutoCloseFD> LocalStore::createTempDirInStore()
/* There is a slight possibility that `tmpDir' gets deleted by /* There is a slight possibility that `tmpDir' gets deleted by
the GC between createTempDir() and when we acquire a lock on it. the GC between createTempDir() and when we acquire a lock on it.
We'll repeat until 'tmpDir' exists and we've locked it. */ We'll repeat until 'tmpDir' exists and we've locked it. */
tmpDirFn = createTempDir(config->realStoreDir, "tmp"); tmpDirFn = createTempDir(std::filesystem::path{config->realStoreDir.get()}, "tmp");
tmpDirFd = openDirectory(tmpDirFn); tmpDirFd = openDirectory(tmpDirFn);
if (!tmpDirFd) { if (!tmpDirFd) {
continue; continue;

View file

@ -174,7 +174,7 @@ struct DarwinDerivationBuilder : DerivationBuilderImpl
/* The tmpDir in scope points at the temporary build directory for our derivation. Some packages try different /* The tmpDir in scope points at the temporary build directory for our derivation. Some packages try different
mechanisms to find temporary directories, so we want to open up a broader place for them to put their files, mechanisms to find temporary directories, so we want to open up a broader place for them to put their files,
if needed. */ if needed. */
Path globalTmpDir = canonPath(defaultTempDir(), true); Path globalTmpDir = canonPath(defaultTempDir().string(), true);
/* They don't like trailing slashes on subpath directives */ /* They don't like trailing slashes on subpath directives */
while (!globalTmpDir.empty() && globalTmpDir.back() == '/') while (!globalTmpDir.empty() && globalTmpDir.back() == '/')

View file

@ -676,16 +676,16 @@ void AutoUnmount::cancel()
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
std::string defaultTempDir() std::filesystem::path defaultTempDir()
{ {
return getEnvNonEmpty("TMPDIR").value_or("/tmp"); return getEnvNonEmpty("TMPDIR").value_or("/tmp");
} }
Path createTempDir(const Path & tmpRoot, const Path & prefix, mode_t mode) std::filesystem::path createTempDir(const std::filesystem::path & tmpRoot, const std::string & prefix, mode_t mode)
{ {
while (1) { while (1) {
checkInterrupt(); checkInterrupt();
Path tmpDir = makeTempPath(tmpRoot, prefix); std::filesystem::path tmpDir = makeTempPath(tmpRoot, prefix);
if (mkdir( if (mkdir(
tmpDir.c_str() tmpDir.c_str()
#ifndef _WIN32 // TODO abstract mkdir perms for Windows #ifndef _WIN32 // TODO abstract mkdir perms for Windows
@ -727,11 +727,11 @@ std::pair<AutoCloseFD, Path> createTempFile(const Path & prefix)
return {std::move(fd), tmpl}; return {std::move(fd), tmpl};
} }
Path makeTempPath(const Path & root, const Path & suffix) std::filesystem::path makeTempPath(const std::filesystem::path & root, const std::string & suffix)
{ {
// start the counter at a random value to minimize issues with preexisting temp paths // start the counter at a random value to minimize issues with preexisting temp paths
static std::atomic<uint32_t> counter(std::random_device{}()); static std::atomic<uint32_t> counter(std::random_device{}());
auto tmpRoot = canonPath(root.empty() ? defaultTempDir() : root, true); auto tmpRoot = canonPath(root.empty() ? defaultTempDir().string() : root.string(), true);
return fmt("%1%/%2%-%3%-%4%", tmpRoot, suffix, getpid(), counter.fetch_add(1, std::memory_order_relaxed)); return fmt("%1%/%2%-%3%-%4%", tmpRoot, suffix, getpid(), counter.fetch_add(1, std::memory_order_relaxed));
} }

View file

@ -334,7 +334,8 @@ typedef std::unique_ptr<DIR, DIRDeleter> AutoCloseDir;
/** /**
* Create a temporary directory. * Create a temporary directory.
*/ */
Path createTempDir(const Path & tmpRoot = "", const Path & prefix = "nix", mode_t mode = 0755); std::filesystem::path
createTempDir(const std::filesystem::path & tmpRoot = "", const std::string & prefix = "nix", mode_t mode = 0755);
/** /**
* Create a temporary file, returning a file handle and its path. * Create a temporary file, returning a file handle and its path.
@ -344,7 +345,7 @@ std::pair<AutoCloseFD, Path> createTempFile(const Path & prefix = "nix");
/** /**
* Return `TMPDIR`, or the default temporary directory if unset or empty. * Return `TMPDIR`, or the default temporary directory if unset or empty.
*/ */
Path defaultTempDir(); std::filesystem::path defaultTempDir();
/** /**
* Interpret `exe` as a location in the ambient file system and return * Interpret `exe` as a location in the ambient file system and return
@ -358,7 +359,7 @@ bool isExecutableFileAmbient(const std::filesystem::path & exe);
* The constructed path looks like `<root><suffix>-<pid>-<unique>`. To create a * The constructed path looks like `<root><suffix>-<pid>-<unique>`. To create a
* path nested in a directory, provide a suffix starting with `/`. * path nested in a directory, provide a suffix starting with `/`.
*/ */
Path makeTempPath(const Path & root, const Path & suffix = ".tmp"); std::filesystem::path makeTempPath(const std::filesystem::path & root, const std::string & suffix = ".tmp");
/** /**
* Used in various places. * Used in various places.