LibCore: Add Windows version of DirIterator

Co-authored-by: stasoid <stasoid@yahoo.com>
This commit is contained in:
Cameron Youell
2023-08-30 17:19:29 +10:00
committed by Andrew Kaster
parent c5219b0193
commit 94601e1ffd
8 changed files with 238 additions and 21 deletions

View File

@@ -5,7 +5,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Vector.h>
#include <LibCore/DirIterator.h>
#include <errno.h>
#include <fcntl.h>
@@ -13,32 +12,36 @@
namespace Core {
struct DirIterator::Impl {
DIR* dir { nullptr };
};
DirIterator::DirIterator(ByteString path, Flags flags)
: m_path(move(path))
: m_impl(make<Impl>())
, m_path(move(path))
, m_flags(flags)
{
m_dir = opendir(m_path.characters());
if (!m_dir) {
m_impl->dir = opendir(m_path.characters());
if (!m_impl->dir) {
m_error = Error::from_errno(errno);
}
}
DirIterator::~DirIterator()
{
if (m_dir) {
closedir(m_dir);
m_dir = nullptr;
if (m_impl && m_impl->dir) {
closedir(m_impl->dir);
m_impl->dir = nullptr;
}
}
DirIterator::DirIterator(DirIterator&& other)
: m_dir(other.m_dir)
: m_impl(move(other.m_impl))
, m_error(move(other.m_error))
, m_next(move(other.m_next))
, m_path(move(other.m_path))
, m_flags(other.m_flags)
{
other.m_dir = nullptr;
}
static constexpr bool dirent_has_d_type =
@@ -50,12 +53,12 @@ static constexpr bool dirent_has_d_type =
bool DirIterator::advance_next()
{
if (!m_dir)
if (!m_impl || !m_impl->dir)
return false;
while (true) {
errno = 0;
auto* de = readdir(m_dir);
auto* de = readdir(m_impl->dir);
if (!de) {
if (errno != 0) {
m_error = Error::from_errno(errno);
@@ -68,7 +71,7 @@ bool DirIterator::advance_next()
if constexpr (dirent_has_d_type)
m_next = DirectoryEntry::from_dirent(*de);
else
m_next = DirectoryEntry::from_stat(m_dir, *de);
m_next = DirectoryEntry::from_stat(m_impl->dir, *de);
if (m_next->name.is_empty())
return false;
@@ -86,7 +89,7 @@ bool DirIterator::advance_next()
// the calling code will be given the raw unknown type.
if ((m_flags & Flags::NoStat) == 0 && m_next->type == DirectoryEntry::Type::Unknown) {
struct stat statbuf;
if (fstatat(dirfd(m_dir), de->d_name, &statbuf, AT_SYMLINK_NOFOLLOW) < 0) {
if (fstatat(dirfd(m_impl->dir), de->d_name, &statbuf, AT_SYMLINK_NOFOLLOW) < 0) {
m_error = Error::from_errno(errno);
dbgln("DirIteration error: {}", m_error.value());
return false;
@@ -137,9 +140,9 @@ ByteString DirIterator::next_full_path()
int DirIterator::fd() const
{
if (!m_dir)
if (!m_impl || !m_impl->dir)
return -1;
return dirfd(m_dir);
return dirfd(m_impl->dir);
}
}