DirIterator.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Vector.h>
  7. #include <LibCore/DirIterator.h>
  8. #include <errno.h>
  9. #include <unistd.h>
  10. namespace Core {
  11. DirIterator::DirIterator(String path, Flags flags)
  12. : m_path(move(path))
  13. , m_flags(flags)
  14. {
  15. m_dir = opendir(m_path.characters());
  16. if (!m_dir) {
  17. m_error = errno;
  18. }
  19. }
  20. DirIterator::~DirIterator()
  21. {
  22. if (m_dir) {
  23. closedir(m_dir);
  24. m_dir = nullptr;
  25. }
  26. }
  27. DirIterator::DirIterator(DirIterator&& other)
  28. : m_dir(other.m_dir)
  29. , m_error(other.m_error)
  30. , m_next(move(other.m_next))
  31. , m_path(move(other.m_path))
  32. , m_flags(other.m_flags)
  33. {
  34. other.m_dir = nullptr;
  35. }
  36. bool DirIterator::advance_next()
  37. {
  38. if (!m_dir)
  39. return false;
  40. while (true) {
  41. errno = 0;
  42. auto* de = readdir(m_dir);
  43. if (!de) {
  44. m_error = errno;
  45. m_next = String();
  46. return false;
  47. }
  48. m_next = de->d_name;
  49. if (m_next.is_null())
  50. return false;
  51. if (m_flags & Flags::SkipDots && m_next.starts_with('.'))
  52. continue;
  53. if (m_flags & Flags::SkipParentAndBaseDir && (m_next == "." || m_next == ".."))
  54. continue;
  55. return !m_next.is_empty();
  56. }
  57. }
  58. bool DirIterator::has_next()
  59. {
  60. if (!m_next.is_null())
  61. return true;
  62. return advance_next();
  63. }
  64. String DirIterator::next_path()
  65. {
  66. if (m_next.is_null())
  67. advance_next();
  68. auto tmp = m_next;
  69. m_next = String();
  70. return tmp;
  71. }
  72. String DirIterator::next_full_path()
  73. {
  74. StringBuilder builder;
  75. builder.append(m_path);
  76. if (!m_path.ends_with('/'))
  77. builder.append('/');
  78. builder.append(next_path());
  79. return builder.to_string();
  80. }
  81. String find_executable_in_path(String filename)
  82. {
  83. if (filename.starts_with('/')) {
  84. if (access(filename.characters(), X_OK) == 0)
  85. return filename;
  86. return {};
  87. }
  88. for (auto directory : String { getenv("PATH") }.split(':')) {
  89. auto fullpath = String::formatted("{}/{}", directory, filename);
  90. if (access(fullpath.characters(), X_OK) == 0)
  91. return fullpath;
  92. }
  93. return {};
  94. }
  95. int DirIterator::fd() const
  96. {
  97. if (!m_dir)
  98. return -1;
  99. return dirfd(m_dir);
  100. }
  101. }