iterator.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. FileTree_.Reset(yfts_open(Trees_, Options_.FtsOptions, Options_.Cmp));
  56. if (!FileTree_.Get() || FileTree_->fts_cur->fts_link->fts_errno) {
  57. ythrow TError(FileTree_.Get() ? FileTree_->fts_cur->fts_link->fts_errno : LastSystemError()) << "can not open '" << Path_ << "'";
  58. }
  59. }
  60. inline FTSENT* Next() {
  61. FTSENT* ret = yfts_read(FileTree_.Get());
  62. if (ret) {
  63. if ((size_t)(ret->fts_level + 1) > Options_.MaxLevel) {
  64. yfts_set(FileTree_.Get(), ret, FTS_SKIP);
  65. }
  66. } else {
  67. const int err = LastSystemError();
  68. if (err) {
  69. ythrow TError(err) << "error while iterating " << Path_;
  70. }
  71. }
  72. return ret;
  73. }
  74. inline void Skip(FTSENT* ent) {
  75. yfts_set(FileTree_.Get(), ent, FTS_SKIP);
  76. }
  77. private:
  78. TOptions Options_;
  79. TString Path_;
  80. char* Trees_[2];
  81. THolder<FTS, TFtsDestroy> FileTree_;
  82. };