iterator.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #pragma once
  2. #include "fts.h"
  3. #include <util/system/error.h>
  4. #include <util/generic/ptr.h>
  5. #include <util/generic/iterator.h>
  6. #include <util/generic/yexception.h>
  7. /// Note this magic API traverses directory hierarchy
  8. class TDirIterator: public TInputRangeAdaptor<TDirIterator> {
  9. struct TFtsDestroy {
  10. static inline void Destroy(FTS* f) noexcept {
  11. yfts_close(f);
  12. }
  13. };
  14. public:
  15. class TError: public TSystemError {
  16. public:
  17. inline TError(int err)
  18. : TSystemError(err)
  19. {
  20. }
  21. };
  22. using TCompare = int (*)(const FTSENT**, const FTSENT**);
  23. struct TOptions {
  24. inline TOptions() {
  25. Init(FTS_PHYSICAL);
  26. }
  27. inline TOptions(int opts) {
  28. Init(opts);
  29. }
  30. inline TOptions& SetMaxLevel(size_t level) noexcept {
  31. MaxLevel = level;
  32. return *this;
  33. }
  34. inline TOptions& SetSortFunctor(TCompare cmp) noexcept {
  35. Cmp = cmp;
  36. return *this;
  37. }
  38. TOptions& SetSortByName() noexcept;
  39. int FtsOptions;
  40. size_t MaxLevel;
  41. TCompare Cmp;
  42. private:
  43. inline void Init(int opts) noexcept {
  44. FtsOptions = opts | FTS_NOCHDIR;
  45. MaxLevel = Max<size_t>();
  46. Cmp = nullptr;
  47. }
  48. };
  49. inline TDirIterator(const TString& path, const TOptions& options = TOptions())
  50. : Options_(options)
  51. , Path_(path)
  52. {
  53. Trees_[0] = Path_.begin();
  54. Trees_[1] = nullptr;
  55. ClearLastSystemError();
  56. FileTree_.Reset(yfts_open(Trees_, Options_.FtsOptions, Options_.Cmp));
  57. const int err = LastSystemError();
  58. if (err) {
  59. ythrow TError(err) << "can not open '" << Path_ << "'";
  60. }
  61. }
  62. inline FTSENT* Next() {
  63. FTSENT* ret = yfts_read(FileTree_.Get());
  64. if (ret) {
  65. if ((size_t)(ret->fts_level + 1) > Options_.MaxLevel) {
  66. yfts_set(FileTree_.Get(), ret, FTS_SKIP);
  67. }
  68. } else {
  69. const int err = LastSystemError();
  70. if (err) {
  71. ythrow TError(err) << "error while iterating " << Path_;
  72. }
  73. }
  74. return ret;
  75. }
  76. inline void Skip(FTSENT* ent) {
  77. yfts_set(FileTree_.Get(), ent, FTS_SKIP);
  78. }
  79. private:
  80. TOptions Options_;
  81. TString Path_;
  82. char* Trees_[2];
  83. THolder<FTS, TFtsDestroy> FileTree_;
  84. };