1
0
Fork 0
mirror of https://github.com/NixOS/nix synced 2024-09-19 10:50:24 -04:00

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) if (resOpt)
return *resOpt; return *resOpt;
else else
throw ExecutableLookupError("Could not find executable '%s'", exe.native()); throw ExecutableLookupError("Could not find executable '%s'", exe.string());
} else { } else {
return exe; return exe;
} }

View file

@ -18,7 +18,7 @@ using namespace nix;
typedef std::map<std::string, std::string> Channels; typedef std::map<std::string, std::string> Channels;
static Channels channels; static Channels channels;
static Path channelsList; static std::filesystem::path channelsList;
// Reads the list of channels. // Reads the list of channels.
static void readChannels() 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)}; auto channelsFD = AutoCloseFD{open(channelsList.c_str(), O_WRONLY | O_CLOEXEC | O_CREAT | O_TRUNC, 0644)};
if (!channelsFD) if (!channelsFD)
throw SysError("opening '%1%' for writing", channelsList); throw SysError("opening '%1%' for writing", channelsList.string());
for (const auto & channel : channels) for (const auto & channel : channels)
writeFull(channelsFD.get(), channel.second + " " + channel.first + "\n"); 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 * Of course, this makes rollbacks to before this point in time
* impossible. */ * 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}) { for (auto & i : std::filesystem::directory_iterator{dir}) {
checkInterrupt(); checkInterrupt();
@ -81,7 +81,7 @@ static int main_nix_collect_garbage(int argc, char * * argv)
}); });
if (removeOld) { if (removeOld) {
std::set<Path> dirsToClean = { std::set<std::filesystem::path> dirsToClean = {
profilesDir(), settings.nixStateDir + "/profiles", dirOf(getDefaultProfile())}; profilesDir(), settings.nixStateDir + "/profiles", dirOf(getDefaultProfile())};
for (auto & dir : dirsToClean) for (auto & dir : dirsToClean)
removeOldGenerations(dir); 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. // 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)) { for (const auto & [_i, buildable] : enumerate(buildables)) {
auto i = _i; auto i = _i;
std::visit(overloaded { std::visit(overloaded {
[&](const BuiltPath::Opaque & bo) { [&](const BuiltPath::Opaque & bo) {
std::string symlink = outLink; auto symlink = outLink;
if (i) symlink += fmt("-%d", i); if (i) symlink += fmt("-%d", i);
store2.addPermRoot(bo.path, absPath(symlink)); store2.addPermRoot(bo.path, absPath(symlink.string()));
}, },
[&](const BuiltPath::Built & bfd) { [&](const BuiltPath::Built & bfd) {
for (auto & output : bfd.outputs) { for (auto & output : bfd.outputs) {
std::string symlink = outLink; auto symlink = outLink;
if (i) symlink += fmt("-%d", i); if (i) symlink += fmt("-%d", i);
if (output.first != "out") symlink += fmt("-%s", output.first); 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()); }, buildable.path.raw());

View file

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

View file

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

View file

@ -19,11 +19,14 @@
#include "users.hh" #include "users.hh"
#include "terminal.hh" #include "terminal.hh"
#include <filesystem>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <iomanip> #include <iomanip>
#include "strings-inline.hh" #include "strings-inline.hh"
namespace fs = std::filesystem;
using namespace nix; using namespace nix;
using namespace nix::flake; using namespace nix::flake;
using json = nlohmann::json; 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.", "If you've set '%s' to a string, try using a path instead.",
templateDir, templateDirAttr->getAttrPathStr()).debugThrow(); templateDir, templateDirAttr->getAttrPathStr()).debugThrow();
std::vector<Path> changedFiles; std::vector<fs::path> changedFiles;
std::vector<Path> conflictedFiles; std::vector<fs::path> conflictedFiles;
std::function<void(const Path & from, const Path & to)> copyDir; std::function<void(const fs::path & from, const fs::path & to)> copyDir;
copyDir = [&](const Path & from, const Path & to) 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(); checkInterrupt();
auto from2 = entry.path().string(); auto from2 = entry.path();
auto to2 = to + "/" + entry.path().filename().string(); auto to2 = to / entry.path().filename();
auto st = lstat(from2); auto st = entry.symlink_status();
if (S_ISDIR(st.st_mode)) auto to_st = fs::symlink_status(to2);
if (fs::is_directory(st))
copyDir(from2, to2); copyDir(from2, to2);
else if (S_ISREG(st.st_mode)) { else if (fs::is_regular_file(st)) {
auto contents = readFile(from2); auto contents = readFile(from2.string());
if (pathExists(to2)) { if (fs::exists(to_st)) {
auto contents2 = readFile(to2); auto contents2 = readFile(to2.string());
if (contents != contents2) { 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); conflictedFiles.push_back(to2);
} else { } else {
notice("skipping identical file: %s", from2); notice("skipping identical file: %s", from2);
} }
continue; continue;
} else } else
writeFile(to2, contents); writeFile(to2.string(), contents);
} }
else if (S_ISLNK(st.st_mode)) { else if (fs::is_symlink(st)) {
auto target = readLink(from2); auto target = fs::read_symlink(from2);
if (pathExists(to2)) { if (fs::exists(to_st)) {
if (readLink(to2) != target) { if (fs::read_symlink(to2) != target) {
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); conflictedFiles.push_back(to2);
} else { } else {
notice("skipping identical file: %s", from2); notice("skipping identical file: %s", from2);
} }
continue; continue;
} else } else
createSymlink(target, to2); fs::create_symlink(target, to2);
} }
else else
throw Error("file '%s' has unsupported type", from2); throw Error("file '%s' has unsupported type", from2);
@ -947,9 +951,9 @@ struct CmdFlakeInitCommon : virtual Args, EvalCommand
copyDir(templateDir, flakeDir); 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", "--" }; 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); runProgram("git", true, args);
} }
auto welcomeText = cursor->maybeGetAttr("welcomeText"); auto welcomeText = cursor->maybeGetAttr("welcomeText");

View file

@ -122,12 +122,12 @@ struct ProfileManifest
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)) { if (std::filesystem::exists(manifestPath)) {
auto json = nlohmann::json::parse(readFile(manifestPath)); auto json = nlohmann::json::parse(readFile(manifestPath.string()));
auto version = json.value("version", 0); auto version = json.value("version", 0);
std::string sUrl; 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. // FIXME: needed because of pure mode; ugly.
state.allowPath(state.store->followLinksToStore(profile)); state.allowPath(state.store->followLinksToStore(profile.string()));
state.allowPath(state.store->followLinksToStore(profile + "/manifest.nix")); 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) { for (auto & packageInfo : packageInfos) {
ProfileElement element; ProfileElement element;

View file

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