iterator.h 2.5 KB

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