Merge pull request #11281 from siddhantk232/path-in-exec

Use `std::filesystem::path` in end executables
This commit is contained in:
John Ericson 2024-08-20 12:35:57 -04:00 committed by GitHub
commit af26fe3934
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 62 additions and 63 deletions

View file

@ -86,7 +86,7 @@ fs::path ExecutablePath::findPath(const fs::path & exe, std::function<bool(const
if (resOpt)
return *resOpt;
else
throw ExecutableLookupError("Could not find executable '%s'", exe.native());
throw ExecutableLookupError("Could not find executable '%s'", exe.string());
} else {
return exe;
}

View file

@ -18,7 +18,7 @@ using namespace nix;
typedef std::map<std::string, std::string> Channels;
static Channels channels;
static Path channelsList;
static std::filesystem::path channelsList;
// Reads the list of channels.
static void readChannels()
@ -42,7 +42,7 @@ static void writeChannels()
{
auto channelsFD = AutoCloseFD{open(channelsList.c_str(), O_WRONLY | O_CLOEXEC | O_CREAT | O_TRUNC, 0644)};
if (!channelsFD)
throw SysError("opening '%1%' for writing", channelsList);
throw SysError("opening '%1%' for writing", channelsList.string());
for (const auto & channel : channels)
writeFull(channelsFD.get(), channel.second + " " + channel.first + "\n");
}

View file

@ -21,11 +21,11 @@ bool dryRun = false;
* Of course, this makes rollbacks to before this point in time
* impossible. */
void removeOldGenerations(std::string dir)
void removeOldGenerations(std::filesystem::path dir)
{
if (access(dir.c_str(), R_OK) != 0) return;
if (access(dir.string().c_str(), R_OK) != 0) return;
bool canWrite = access(dir.c_str(), W_OK) == 0;
bool canWrite = access(dir.string().c_str(), W_OK) == 0;
for (auto & i : std::filesystem::directory_iterator{dir}) {
checkInterrupt();
@ -81,7 +81,7 @@ static int main_nix_collect_garbage(int argc, char * * argv)
});
if (removeOld) {
std::set<Path> dirsToClean = {
std::set<std::filesystem::path> dirsToClean = {
profilesDir(), settings.nixStateDir + "/profiles", dirOf(getDefaultProfile())};
for (auto & dir : dirsToClean)
removeOldGenerations(dir);

View file

@ -43,22 +43,22 @@ static nlohmann::json builtPathsWithResultToJSON(const std::vector<BuiltPathWith
}
// TODO deduplicate with other code also setting such out links.
static void createOutLinks(const Path& outLink, const std::vector<BuiltPathWithResult>& buildables, LocalFSStore& store2)
static void createOutLinks(const std::filesystem::path& outLink, const std::vector<BuiltPathWithResult>& buildables, LocalFSStore& store2)
{
for (const auto & [_i, buildable] : enumerate(buildables)) {
auto i = _i;
std::visit(overloaded {
[&](const BuiltPath::Opaque & bo) {
std::string symlink = outLink;
auto symlink = outLink;
if (i) symlink += fmt("-%d", i);
store2.addPermRoot(bo.path, absPath(symlink));
store2.addPermRoot(bo.path, absPath(symlink.string()));
},
[&](const BuiltPath::Built & bfd) {
for (auto & output : bfd.outputs) {
std::string symlink = outLink;
auto symlink = outLink;
if (i) symlink += fmt("-%d", i);
if (output.first != "out") symlink += fmt("-%s", output.first);
store2.addPermRoot(output.second, absPath(symlink));
store2.addPermRoot(output.second, absPath(symlink.string()));
}
},
}, buildable.path.raw());

View file

@ -117,8 +117,6 @@ struct CmdBundle : InstallableValueCommand
},
});
auto outPathS = store->printStorePath(outPath);
if (!outLink) {
auto * attr = vRes->attrs()->get(evalState->sName);
if (!attr)

View file

@ -78,27 +78,23 @@ struct CmdEval : MixJSON, InstallableValueCommand, MixReadOnlyOption
if (pathExists(*writeTo))
throw Error("path '%s' already exists", *writeTo);
std::function<void(Value & v, const PosIdx pos, const Path & path)> recurse;
std::function<void(Value & v, const PosIdx pos, const std::filesystem::path & path)> recurse;
recurse = [&](Value & v, const PosIdx pos, const Path & path)
recurse = [&](Value & v, const PosIdx pos, const std::filesystem::path & path)
{
state->forceValue(v, pos);
if (v.type() == nString)
// FIXME: disallow strings with contexts?
writeFile(path, v.string_view());
writeFile(path.string(), v.string_view());
else if (v.type() == nAttrs) {
if (mkdir(path.c_str()
#ifndef _WIN32 // TODO abstract mkdir perms for Windows
, 0777
#endif
) == -1)
throw SysError("creating directory '%s'", path);
// TODO abstract mkdir perms for Windows
createDir(path.string(), 0777);
for (auto & attr : *v.attrs()) {
std::string_view name = state->symbols[attr.name];
try {
if (name == "." || name == "..")
throw Error("invalid file name '%s'", name);
recurse(*attr.value, attr.pos, concatStrings(path, "/", name));
recurse(*attr.value, attr.pos, path / name);
} catch (Error & e) {
e.addTrace(
state->positions[attr.pos],

View file

@ -19,11 +19,14 @@
#include "users.hh"
#include "terminal.hh"
#include <filesystem>
#include <nlohmann/json.hpp>
#include <iomanip>
#include "strings-inline.hh"
namespace fs = std::filesystem;
using namespace nix;
using namespace nix::flake;
using json = nlohmann::json;
@ -896,47 +899,48 @@ struct CmdFlakeInitCommon : virtual Args, EvalCommand
"If you've set '%s' to a string, try using a path instead.",
templateDir, templateDirAttr->getAttrPathStr()).debugThrow();
std::vector<Path> changedFiles;
std::vector<Path> conflictedFiles;
std::vector<fs::path> changedFiles;
std::vector<fs::path> conflictedFiles;
std::function<void(const Path & from, const Path & to)> copyDir;
copyDir = [&](const Path & from, const Path & to)
std::function<void(const fs::path & from, const fs::path & to)> copyDir;
copyDir = [&](const fs::path & from, const fs::path & to)
{
createDirs(to);
fs::create_directories(to);
for (auto & entry : std::filesystem::directory_iterator{from}) {
for (auto & entry : fs::directory_iterator{from}) {
checkInterrupt();
auto from2 = entry.path().string();
auto to2 = to + "/" + entry.path().filename().string();
auto st = lstat(from2);
if (S_ISDIR(st.st_mode))
auto from2 = entry.path();
auto to2 = to / entry.path().filename();
auto st = entry.symlink_status();
auto to_st = fs::symlink_status(to2);
if (fs::is_directory(st))
copyDir(from2, to2);
else if (S_ISREG(st.st_mode)) {
auto contents = readFile(from2);
if (pathExists(to2)) {
auto contents2 = readFile(to2);
else if (fs::is_regular_file(st)) {
auto contents = readFile(from2.string());
if (fs::exists(to_st)) {
auto contents2 = readFile(to2.string());
if (contents != contents2) {
printError("refusing to overwrite existing file '%s'\n please merge it manually with '%s'", to2, from2);
printError("refusing to overwrite existing file '%s'\n please merge it manually with '%s'", to2.string(), from2.string());
conflictedFiles.push_back(to2);
} else {
notice("skipping identical file: %s", from2);
}
continue;
} else
writeFile(to2, contents);
writeFile(to2.string(), contents);
}
else if (S_ISLNK(st.st_mode)) {
auto target = readLink(from2);
if (pathExists(to2)) {
if (readLink(to2) != target) {
printError("refusing to overwrite existing file '%s'\n please merge it manually with '%s'", to2, from2);
else if (fs::is_symlink(st)) {
auto target = fs::read_symlink(from2);
if (fs::exists(to_st)) {
if (fs::read_symlink(to2) != target) {
printError("refusing to overwrite existing file '%s'\n please merge it manually with '%s'", to2.string(), from2.string());
conflictedFiles.push_back(to2);
} else {
notice("skipping identical file: %s", from2);
}
continue;
} else
createSymlink(target, to2);
fs::create_symlink(target, to2);
}
else
throw Error("file '%s' has unsupported type", from2);
@ -947,9 +951,9 @@ struct CmdFlakeInitCommon : virtual Args, EvalCommand
copyDir(templateDir, flakeDir);
if (!changedFiles.empty() && pathExists(flakeDir + "/.git")) {
if (!changedFiles.empty() && fs::exists(std::filesystem::path{flakeDir} / ".git")) {
Strings args = { "-C", flakeDir, "add", "--intent-to-add", "--force", "--" };
for (auto & s : changedFiles) args.push_back(s);
for (auto & s : changedFiles) args.emplace_back(s.string());
runProgram("git", true, args);
}
auto welcomeText = cursor->maybeGetAttr("welcomeText");
@ -1274,7 +1278,7 @@ struct CmdFlakeShow : FlakeCommand, MixJSON
if (auto aDescription = aMeta->maybeGetAttr(state->sDescription))
description = aDescription->getString();
}
if (json) {
j.emplace("type", "derivation");
j.emplace("name", name);

View file

@ -122,12 +122,12 @@ struct ProfileManifest
ProfileManifest() { }
ProfileManifest(EvalState & state, const Path & profile)
ProfileManifest(EvalState & state, const std::filesystem::path & profile)
{
auto manifestPath = profile + "/manifest.json";
auto manifestPath = profile / "manifest.json";
if (pathExists(manifestPath)) {
auto json = nlohmann::json::parse(readFile(manifestPath));
if (std::filesystem::exists(manifestPath)) {
auto json = nlohmann::json::parse(readFile(manifestPath.string()));
auto version = json.value("version", 0);
std::string sUrl;
@ -176,12 +176,12 @@ struct ProfileManifest
}
}
else if (pathExists(profile + "/manifest.nix")) {
else if (std::filesystem::exists(profile / "manifest.nix")) {
// FIXME: needed because of pure mode; ugly.
state.allowPath(state.store->followLinksToStore(profile));
state.allowPath(state.store->followLinksToStore(profile + "/manifest.nix"));
state.allowPath(state.store->followLinksToStore(profile.string()));
state.allowPath(state.store->followLinksToStore((profile / "manifest.nix").string()));
auto packageInfos = queryInstalled(state, state.store->followLinksToStore(profile));
auto packageInfos = queryInstalled(state, state.store->followLinksToStore(profile.string()));
for (auto & packageInfo : packageInfos) {
ProfileElement element;

View file

@ -11,6 +11,7 @@
#include "source-accessor.hh"
#include "progress-bar.hh"
#include "eval.hh"
#include <filesystem>
#if __linux__
# include <sys/mount.h>
@ -169,7 +170,7 @@ void chrootHelper(int argc, char * * argv)
if (!pathExists(storeDir)) {
// FIXME: Use overlayfs?
Path tmpDir = createTempDir();
std::filesystem::path tmpDir = createTempDir();
createDirs(tmpDir + storeDir);
@ -178,16 +179,16 @@ void chrootHelper(int argc, char * * argv)
for (auto entry : std::filesystem::directory_iterator{"/"}) {
checkInterrupt();
auto src = entry.path().string();
Path dst = tmpDir + "/" + entry.path().filename().string();
auto src = entry.path();
Path dst = tmpDir / entry.path().filename();
if (pathExists(dst)) continue;
auto st = lstat(src);
if (S_ISDIR(st.st_mode)) {
auto st = entry.symlink_status();
if (std::filesystem::is_directory(st)) {
if (mkdir(dst.c_str(), 0700) == -1)
throw SysError("creating directory '%s'", dst);
if (mount(src.c_str(), dst.c_str(), "", MS_BIND | MS_REC, 0) == -1)
throw SysError("mounting '%s' on '%s'", src, dst);
} else if (S_ISLNK(st.st_mode))
} else if (std::filesystem::is_symlink(st))
createSymlink(readLink(src), dst);
}