Merge pull request #10684 from siddhantk232/rm-readDirectory

Inline the usage of `nix::readDirectory` and remove it
This commit is contained in:
Eelco Dolstra 2024-05-13 15:41:59 +02:00 committed by GitHub
commit 1623249745
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 27 additions and 44 deletions

View file

@ -259,7 +259,7 @@ StringSet NixRepl::completePrefix(const std::string & prefix)
try { try {
auto dir = std::string(cur, 0, slash); auto dir = std::string(cur, 0, slash);
auto prefix2 = std::string(cur, slash + 1); auto prefix2 = std::string(cur, slash + 1);
for (auto & entry : readDirectory(dir == "" ? "/" : dir)) { for (auto & entry : std::filesystem::directory_iterator{dir == "" ? "/" : dir}) {
auto name = entry.path().filename().string(); auto name = entry.path().filename().string();
if (name[0] != '.' && hasPrefix(name, prefix2)) if (name[0] != '.' && hasPrefix(name, prefix2))
completions.insert(prev + entry.path().string()); completions.insert(prev + entry.path().string());

View file

@ -17,10 +17,10 @@ struct State
/* For each activated package, create symlinks */ /* For each activated package, create symlinks */
static void createLinks(State & state, const Path & srcDir, const Path & dstDir, int priority) static void createLinks(State & state, const Path & srcDir, const Path & dstDir, int priority)
{ {
std::vector<std::filesystem::directory_entry> srcFiles; std::filesystem::directory_iterator srcFiles;
try { try {
srcFiles = readDirectory(srcDir); srcFiles = std::filesystem::directory_iterator{srcDir};
} catch (std::filesystem::filesystem_error & e) { } catch (std::filesystem::filesystem_error & e) {
if (e.code() == std::errc::not_a_directory) { if (e.code() == std::errc::not_a_directory) {
warn("not including '%s' in the user environment because it's not a directory", srcDir); warn("not including '%s' in the user environment because it's not a directory", srcDir);

View file

@ -161,7 +161,7 @@ void LocalStore::findTempRoots(Roots & tempRoots, bool censor)
{ {
/* Read the `temproots' directory for per-process temporary root /* Read the `temproots' directory for per-process temporary root
files. */ files. */
for (auto & i : readDirectory(tempRootsDir)) { for (auto & i : std::filesystem::directory_iterator{tempRootsDir}) {
auto name = i.path().filename().string(); auto name = i.path().filename().string();
if (name[0] == '.') { if (name[0] == '.') {
// Ignore hidden files. Some package managers (notably portage) create // Ignore hidden files. Some package managers (notably portage) create
@ -228,7 +228,7 @@ void LocalStore::findRoots(const Path & path, std::filesystem::file_type type, R
type = std::filesystem::symlink_status(path).type(); type = std::filesystem::symlink_status(path).type();
if (type == std::filesystem::file_type::directory) { if (type == std::filesystem::file_type::directory) {
for (auto & i : readDirectory(path)) for (auto & i : std::filesystem::directory_iterator{path})
findRoots(i.path().string(), i.symlink_status().type(), roots); findRoots(i.path().string(), i.symlink_status().type(), roots);
} }

View file

@ -345,7 +345,7 @@ void initPlugins()
for (const auto & pluginFile : settings.pluginFiles.get()) { for (const auto & pluginFile : settings.pluginFiles.get()) {
std::vector<std::filesystem::path> pluginFiles; std::vector<std::filesystem::path> pluginFiles;
try { try {
auto ents = readDirectory(pluginFile); auto ents = std::filesystem::directory_iterator{pluginFile};
for (const auto & ent : ents) for (const auto & ent : ents)
pluginFiles.emplace_back(ent.path()); pluginFiles.emplace_back(ent.path());
} catch (std::filesystem::filesystem_error & e) { } catch (std::filesystem::filesystem_error & e) {

View file

@ -83,7 +83,7 @@ protected:
{ {
StorePathSet paths; StorePathSet paths;
for (auto & entry : readDirectory(binaryCacheDir)) { for (auto & entry : std::filesystem::directory_iterator{binaryCacheDir}) {
auto name = entry.path().filename().string(); auto name = entry.path().filename().string();
if (name.size() != 40 || if (name.size() != 40 ||
!hasSuffix(name, ".narinfo")) !hasSuffix(name, ".narinfo"))

View file

@ -1406,7 +1406,7 @@ bool LocalStore::verifyStore(bool checkContents, RepairFlag repair)
printInfo("checking link hashes..."); printInfo("checking link hashes...");
for (auto & link : readDirectory(linksDir)) { for (auto & link : std::filesystem::directory_iterator{linksDir}) {
auto name = link.path().filename(); auto name = link.path().filename();
printMsg(lvlTalkative, "checking contents of '%s'", name); printMsg(lvlTalkative, "checking contents of '%s'", name);
PosixSourceAccessor accessor; PosixSourceAccessor accessor;
@ -1498,7 +1498,7 @@ LocalStore::VerificationResult LocalStore::verifyAllValidPaths(RepairFlag repair
database and the filesystem) in the loop below, in order to catch database and the filesystem) in the loop below, in order to catch
invalid states. invalid states.
*/ */
for (auto & i : readDirectory(realStoreDir)) { for (auto & i : std::filesystem::directory_iterator{realStoreDir.to_string()}) {
try { try {
storePathsInStoreDir.insert({i.path().filename().string()}); storePathsInStoreDir.insert({i.path().filename().string()});
} catch (BadStorePath &) { } } catch (BadStorePath &) { }

View file

@ -144,8 +144,7 @@ static void canonicalisePathMetaData_(
#endif #endif
if (S_ISDIR(st.st_mode)) { if (S_ISDIR(st.st_mode)) {
std::vector<std::filesystem::directory_entry> entries = readDirectory(path); for (auto & i : std::filesystem::directory_iterator{path})
for (auto & i : entries)
canonicalisePathMetaData_( canonicalisePathMetaData_(
i.path().string(), i.path().string(),
#ifndef _WIN32 #ifndef _WIN32

View file

@ -37,7 +37,7 @@ std::pair<Generations, std::optional<GenerationNumber>> findGenerations(Path pro
std::filesystem::path profileDir = dirOf(profile); std::filesystem::path profileDir = dirOf(profile);
auto profileName = std::string(baseNameOf(profile)); auto profileName = std::string(baseNameOf(profile));
for (auto & i : readDirectory(profileDir.string())) { for (auto & i : std::filesystem::directory_iterator{profileDir}) {
if (auto n = parseName(profileName, i.path().filename().string())) { if (auto n = parseName(profileName, i.path().filename().string())) {
auto path = i.path().string(); auto path = i.path().string();
gens.push_back({ gens.push_back({

View file

@ -21,10 +21,13 @@ void builtinUnpackChannel(
unpackTarfile(src, out); unpackTarfile(src, out);
auto entries = readDirectory(out); auto entries = std::filesystem::directory_iterator{out};
if (entries.size() != 1) auto fileName = entries->path().string();
auto fileCount = std::distance(std::filesystem::begin(entries), std::filesystem::end(entries));
if (fileCount != 1)
throw Error("channel tarball '%s' contains more than one file", src); throw Error("channel tarball '%s' contains more than one file", src);
std::filesystem::rename(entries[0].path().string(), (out + "/" + channelName)); std::filesystem::rename(fileName, (out + "/" + channelName));
} }
} }

View file

@ -222,20 +222,6 @@ Path readLink(const Path & path)
} }
std::vector<fs::directory_entry> readDirectory(const Path & path)
{
std::vector<fs::directory_entry> entries;
entries.reserve(64);
for (auto & entry : fs::directory_iterator{path}) {
checkInterrupt();
entries.push_back(std::move(entry));
}
return entries;
}
std::string readFile(const Path & path) std::string readFile(const Path & path)
{ {
AutoCloseFD fd = toDescriptor(open(path.c_str(), O_RDONLY AutoCloseFD fd = toDescriptor(open(path.c_str(), O_RDONLY

View file

@ -122,12 +122,6 @@ Path readLink(const Path & path);
*/ */
Descriptor openDirectory(const std::filesystem::path & path); Descriptor openDirectory(const std::filesystem::path & path);
/**
* Read the contents of a directory. The entries `.` and `..` are
* removed.
*/
std::vector<std::filesystem::directory_entry> readDirectory(const Path & path);
/** /**
* Read the contents of a file into a string. * Read the contents of a file into a string.
*/ */

View file

@ -64,7 +64,7 @@ static CgroupStats destroyCgroup(const std::filesystem::path & cgroup, bool retu
/* Otherwise, manually kill every process in the subcgroups and /* Otherwise, manually kill every process in the subcgroups and
this cgroup. */ this cgroup. */
for (auto & entry : readDirectory(cgroup)) { for (auto & entry : std::filesystem::directory_iterator{cgroup}) {
if (entry.symlink_status().type() != std::filesystem::file_type::directory) continue; if (entry.symlink_status().type() != std::filesystem::file_type::directory) continue;
destroyCgroup(cgroup / entry.path().filename(), false); destroyCgroup(cgroup / entry.path().filename(), false);
} }

View file

@ -132,7 +132,7 @@ SourceAccessor::DirEntries PosixSourceAccessor::readDirectory(const CanonPath &
{ {
assertNoSymlinks(path); assertNoSymlinks(path);
DirEntries res; DirEntries res;
for (auto & entry : nix::readDirectory(makeAbsPath(path).string())) { for (auto & entry : std::filesystem::directory_iterator{makeAbsPath(path)}) {
auto type = [&]() -> std::optional<Type> { auto type = [&]() -> std::optional<Type> {
std::filesystem::file_type nativeType; std::filesystem::file_type nativeType;
try { try {

View file

@ -124,7 +124,7 @@ void closeMostFDs(const std::set<int> & exceptions)
{ {
#if __linux__ #if __linux__
try { try {
for (auto & s : readDirectory("/proc/self/fd")) { for (auto & s : std::filesystem::directory_iterator{"/proc/self/fd"}) {
auto fd = std::stoi(s.path().filename()); auto fd = std::stoi(s.path().filename());
if (!exceptions.count(fd)) { if (!exceptions.count(fd)) {
debug("closing leaked FD %d", fd); debug("closing leaked FD %d", fd);

View file

@ -27,7 +27,7 @@ void removeOldGenerations(std::string dir)
bool canWrite = access(dir.c_str(), W_OK) == 0; bool canWrite = access(dir.c_str(), W_OK) == 0;
for (auto & i : readDirectory(dir)) { for (auto & i : std::filesystem::directory_iterator{dir}) {
checkInterrupt(); checkInterrupt();
auto path = i.path().string(); auto path = i.path().string();

View file

@ -866,7 +866,7 @@ struct CmdFlakeInitCommon : virtual Args, EvalCommand
{ {
createDirs(to); createDirs(to);
for (auto & entry : readDirectory(from)) { for (auto & entry : std::filesystem::directory_iterator{from}) {
auto from2 = entry.path().string(); auto from2 = entry.path().string();
auto to2 = to + "/" + entry.path().filename().string(); auto to2 = to + "/" + entry.path().filename().string();
auto st = lstat(from2); auto st = lstat(from2);

View file

@ -115,9 +115,10 @@ std::tuple<StorePath, Hash> prefetchFile(
/* If the archive unpacks to a single file/directory, then use /* If the archive unpacks to a single file/directory, then use
that as the top-level. */ that as the top-level. */
auto entries = readDirectory(unpacked); auto entries = std::filesystem::directory_iterator{unpacked};
if (entries.size() == 1) auto file_count = std::distance(entries, std::filesystem::directory_iterator{});
tmpFile = entries[0].path(); if (file_count == 1)
tmpFile = entries->path();
else else
tmpFile = unpacked; tmpFile = unpacked;
} }

View file

@ -248,7 +248,7 @@ void chrootHelper(int argc, char * * argv)
if (mount(realStoreDir.c_str(), (tmpDir + storeDir).c_str(), "", MS_BIND, 0) == -1) if (mount(realStoreDir.c_str(), (tmpDir + storeDir).c_str(), "", MS_BIND, 0) == -1)
throw SysError("mounting '%s' on '%s'", realStoreDir, storeDir); throw SysError("mounting '%s' on '%s'", realStoreDir, storeDir);
for (auto entry : readDirectory("/")) { for (auto entry : std::filesystem::directory_iterator{"/"}) {
auto src = entry.path().string(); auto src = entry.path().string();
Path dst = tmpDir + "/" + entry.path().filename().string(); Path dst = tmpDir + "/" + entry.path().filename().string();
if (pathExists(dst)) continue; if (pathExists(dst)) continue;